I need to generate unique id's for multiple sentences in a longer narrative (where multiple users can be performing the same action, at the same time, on different machines).
I considered doing new Date().getTime()
(and perhaps concatenating a username
) but as the id's were generated in a loop whilst iterating over the sentences, I found duplicates were created (as generation could occur at the same millisecond).
So I am currently playing around with:
var random1 = Math.floor((Math.random() * 10000) + 1).toString(36);
var random2 = Math.floor((Math.random() * 10000) + 1);
var random3 = Math.floor((Math.random() * 10000) + 1);
var id = random1 + random2 + random3;
// generates things like:
// 1h754278042
// 58o83798349
// 3ls28055962
It occurred to me though (admittedly, as someone who has not pondered unique/random/crypto issues much), that perhaps joining three random numbers isn't any more random that one random number?
Is generating and concatenating 3 Math.random()
values more random than 1 Math.random()
value?
This answer (https://security.stackexchange.com/a/124003) states:
If the random generator really produces random data then it will not matter.
But I'm not sure how that applies to the usage of Math.random()
.
Edit:
Scenario is client side on web and not for security, just to ensure that each sentence has a unique id in the database.
Edit:
I ended up implementing:
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
var id = guid();
From: https://stackoverflow.com/a/105074/1063287
Also see comment on that answer:
Actually, the RFC allows for UUIDs that are created from random numbers. You just have to twiddle a couple of bits to identify it as such. See section 4.4. Algorithms for Creating a UUID from Truly Random or Pseudo-Random Numbers: rfc-archive.org/getrfc.php?rfc=4122