ai / nanoid

A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript

Home Page:https://zelark.github.io/nano-id-cc/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

qcyblm opened this issue · comments

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.

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

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

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