adnan kamili - 2 months ago 15

Javascript Question

I have a use case where I need to generate alpha numeric capital case strings of length 25, so the total possible unique combinations are very high:

`36 pow (25) = 808281277464764060643139600456536293376`

The string is to be stored in

`MySql`

`unique`

`true`

I am using following code to generate the string:

`const Chance = require('chance');`

const chance = new Chance(Date.now() + Math.random());

let randomStr = chance.string({length: 25,

pool: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'});

console.log(randomStr);

Node.js can run in cluster mode, so value of timestamp can be same for different requests so I also added

`Math.random()`

`MySql`

Answer

Is this enough to ensure that MySQL unique constraint won't be violated by the random strings.

36^{25} has 129 bit. If we apply the birthday problem, then you're likely getting a collision around 2^{64} strings. You'll probably generate much less than that. This is only true provided that you use a good randomness source.

`Math.random()`

is **not** a good randomness source.

Source (Stackoverflow)

Comments