This relates to this question. I am using the code below from this answer to generate a UUID in JavaScript:
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); });
This solution appeared to be working fine, but I am getting collisions. Here's what I have:
What is causing this issue and how can I avoid it?
Use encapsulation, create a UUID factory object, where you save old ones in a set, then every time check is the new UUID exist or no, then return it only if it doesn't exist, else repeat.
A collision is possible but the total number of unique keys generated is so large that the possibility of a collision is almost zero. As per Wikipedia, the number of UUIDs generated to have atleast 1 collision is 2.71 quintillion.
The principle doesn't change, UUID generation is really random—meaning you can consider the generation of UUIDs to to be independent events from one another. In other words, creating UUIDs from different computers does not change anything, it is incredibly unlikely that a collision will occur.
Introduction to JavaScript UUID. A universally unique identifier (UUID) is an identifier of the 128-bit value that is used in the construction of software. Each bit present in the value differs by the meaning as several variants are considered.
My best guess is that Math.random()
is broken on your system for some reason (bizarre as that sounds). This is the first report I've seen of anyone getting collisions.
node-uuid
has a test harness that you can use to test the distribution of hex digits in that code. If that looks okay then it's not Math.random()
, so then try substituting the UUID implementation you're using into the uuid()
method there and see if you still get good results.
[Update: Just saw Veselin's report about the bug with Math.random()
at startup. Since the problem is only at startup, the node-uuid
test is unlikely to be useful. I'll comment in more detail on the devoluk.com link.]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With