ai / nanoid

A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript
https://zelark.github.io/nano-id-cc/
MIT License
24.33k stars 788 forks source link

Of the 9 randomly generated numbers, there are more than two duplicate values #396

Closed qcyblm closed 1 year ago

qcyblm commented 1 year ago
import { customAlphabet } from "nanoid/async";
const nanoid = async () => {
  const alphabet = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  return await customAlphabet(alphabet.join(""), 1)();
};

for (let i = 0; i < 9; i++) {
  console.log(await nanoid());
}

The output: 9 5 8 4 7 2 3 8 6 9 4 3 6 2 3 9 4 3

Expectation: Within the known range, it is repeated when it is less than or equal to no duplicates, and if it is greater than the known range.

ai commented 1 year ago

This is how random numbers works. They could get duplicated.

Otherwise, the attacker will be able to predict the next number by previous numbers.

ai commented 1 year ago

Try with Math.random and you will see the same duplicated.

for (let i = 0; i < 9; i++) console.log(Math.round(Math.random() * 10))
6
6
4
10
10
10
7
2
5