Skip to content

Instantly share code, notes, and snippets.

@hugowetterberg
Last active August 16, 2018 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hugowetterberg/8019011 to your computer and use it in GitHub Desktop.
Save hugowetterberg/8019011 to your computer and use it in GitHub Desktop.
Simple "spec-driven" v4 UUID implementation
// Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where
// x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g.,
// f47ac10b-58cc-4372-a567-0e02b2c3d479).
// See: http://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29
function uuid() {
var reservedBitValues = ['8','9','a','b'];
return Array.prototype.map.call("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx", function mapUUID(c) {
if (c == "x") {
return Math.round(Math.random()*16-0.5).toString(16);
}
else if (c == "y") {
return reservedBitValues[Math.round(Math.random()*reservedBitValues.length-0.5)]
}
else {
return c;
}
}).join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment