Skip to content

Instantly share code, notes, and snippets.

@TikiTDO
Last active July 2, 2016 12:15
Show Gist options
  • Save TikiTDO/a97682d1aa934ed88c86a6d11c61e20c to your computer and use it in GitHub Desktop.
Save TikiTDO/a97682d1aa934ed88c86a6d11c61e20c to your computer and use it in GitHub Desktop.
A reasonably fast, yet still readable implementation of UUID v4 in JS. Just about the fastest possible without ASM and extensive loop unrolling.
// RFC-4122 - UUID from Crypto Random Source (Version 4)
// https://www.ietf.org/rfc/rfc4122.txt
(function () {
var crypto = self.crypto || self.msCrypto;
var hex_values = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
var template = 'xxxxxxxx-xxxx-4xxx-Rxxx-xxxxxxxxxxxx';
var template_length = template.length;
Math.uuid = function() {
// Generate 16 random 8-bit values, which will be clamped down to 4-bits below
var byte_array = new Uint8Array(16);
crypto.getRandomValues(byte_array);
// Use the above values to generate the UUID
var uuid = "";
var template_index = 0;
var quad = -1;
// Iterate over the UUID template
for (template_index = 0; template_index < template_length; template_index++) {
var char = template[template_index];
// Copy '-' and the RFC-4122 version number from template into UUID
if (char == '-' || char == '4') uuid += char;
// Populate the random values into UUID
else {
// Alternate high and low order quads
var hex = (++quad & 1 ? byte_array[quad >> 1] >> 4 : byte_array[quad >> 1] & 0xF);
// Append the variant code 10xx, for the RFC-4122 variant of UUIDs
if (char == 'R') uuid += hex_values[hex & 0x3 | 0x8];
// Append the hex value for a normal quad
else uuid += hex_values[hex];
}
}
// Return the resulting UUID
return uuid;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment