ulid / javascript

Universally Unique Lexicographically Sortable Identifier
MIT License
3.04k stars 107 forks source link

Random bias? #81

Open skandragon opened 3 years ago

skandragon commented 3 years ago

From the code:

export function randomChar(prng) {
    let rand = Math.floor(prng() * ENCODING_LEN);
    if (rand === ENCODING_LEN) {
        rand = ENCODING_LEN - 1;
    }
    return ENCODING.charAt(rand);
}

I believe this biases the final character in the ENCODING array, which has two different random values it can be created from.

I believe what you want is to do is select a new random number in this case, since while it is difficult to get this value (a 1 in 256 chance) that is still an increase in bias.

While the increase is small, it feels like using a strong prng only to add unnecessary bias should be addressed.