Skip to content

Instantly share code, notes, and snippets.

@TinyExplosions
Created May 28, 2014 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TinyExplosions/75238d44be30a0511408 to your computer and use it in GitHub Desktop.
Save TinyExplosions/75238d44be30a0511408 to your computer and use it in GitHub Desktop.
// based on http://stackoverflow.com/a/873856
var UUIDs = {};
var createUUID = function() {
// http://www.ietf.org/rfc/rfc4122.txt
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = "-";
var uuid = s.join("");
return uuid;
};
var checkUUID = function(idx) {
if ((idx % 1000) === 0) {
process.stdout.write(". ");
}
var uuid = createUUID();
if (uuid in UUIDs) {
console.log("UUID Collision at point", idx, uuid, "ain't unique");
return false;
} else {
UUIDs[uuid] = true;
return true;
}
};
var runTest = function(iterations) {
console.time('UUID Test Time');
for (var i = 1; i <= iterations; i++) {
if (!checkUUID(i)) {
process.stdout.write("\n");
console.log("Test Failed");
console.timeEnd('UUID Test Time');
return;
}
}
process.stdout.write("\n");
console.log("Test Completed Successfully");
console.timeEnd('UUID Test Time');
return;
};
module.exports = runTest(100);
@TinyExplosions
Copy link
Author

Quick test create n UUID's and check for uniqueness. Used so far on 10 million generated UUID's with no duplicates found.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment