4 ms·
Can someone clarify this statement from the original nanoID site (https://github.com/ai/nanoid https://github.com/ai/nanoid) for me? "random % alphabet is a pop
by hangonhn 4y ago
Can someone clarify this statement from the original nanoID site (https://github.com/ai/nanoid https://github.com/ai/nanoid) for me?
"random % alphabet is a popular mistake to make when coding an ID generator. The distribution will not be even; there will be a lower chance for some symbols to appear compared to others."
If random is picked such that it's in the range of alphabet (i.e. 0 to 25), then the bias should not exist, right? Is that what he's alluding to? Thanks in advance.
- jeremyw 4y agoYes, you must match your RNG values to an integer multiple of your alphabet size, or there will be bias on modulo. Filter, smear bits, etc. More explanation here: https://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator https://stackoverflow.com/questions/10984974/why-do-people-s...
- ksbrooksjr 4y agoJavascript random number generators don't let you choose an arbitrary range. So if you have an alphabet of 26 characters (0-25) you would have to generate a random number by running: crypto.getRandomValues(new Uint8Array(1))[0] % 32 And then filter out the value if it falls outside of your range (0-25).