▲ | egroat a day ago | |
I was going to disagree with you; and I was going to use a very simple function to do it `randString(length, alphabet)` where alphabet is defaulted - as azAZ09 is a good default. However, on many non-trivial projects I've worked on we ended up making the default explicit and then creating wrappers for specific use cases (i.e. randFileName, randFilePath not being case sensitive on some platforms and randTestFilePath including additional characters for tests but production variants sticking to portable sets). Its further worth noting that rarely do I allow the default global random to be used and instead dependency inject it via params/factories. | ||
▲ | WorldMaker a day ago | parent [-] | |
JS is a fun language where argument defaults can accidentally shoot you in the foot because of no runtime type checking of argument application. With your example, you might want to map a bunch of lengths through it, which in simplest form might look:
The classic surprise is that map provides 2 arguments with the second argument being the index of the array. Depending on how `randString(length, alphabet)` uses its alphabet it might just use the string form of the index so you accidentally get random strings of n length '0' then '1' then '2', etc.(The most common case of this problem in JS is probably `parseInt(string, radix = 10)`. Accidental arbitrary radix from an index parameter is a fun way to get unexpected numbers back from your array of strings.) |