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.62k stars 790 forks source link

The length of the generated characters is not the defined size #272

Closed haishangfeng closed 3 years ago

haishangfeng commented 3 years ago

nodejs

import { customAlphabet } from 'nanoid';
const v_code = customAlphabet ('1234567890', 4);

I used the above code to generate a random number with a length of 4 digits, But sometimes the random number generated is only 3 digits, and the probability of this happening is very high.

ai commented 3 years ago

Do you convert v_code to Number type (for instance with parseInt)?

Maybe codes with leading 0 is converted to 3-digits number?

const id = `0123`
parseInt(id) //=> 123
haishangfeng commented 3 years ago

no, I quote directly。

const random4 = Math.floor(Math.random()*(8999))+1000; So how to use customAlphabet to generate four fixed random numbers? such as above code

ai commented 3 years ago

So how to use customAlphabet to generate four fixed random numbers?

let first = customAlphabet ('123456789', 1)
let tail = customAlphabet ('1234567890', 3)

function getCode4 () {
  return first() + tail()
}
haishangfeng commented 3 years ago

Good job,tks very much.