Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
simple uuid generator for evergreen browsers
// see https://tools.ietf.org/html/rfc4122#section-4.4
function uuid () {
var seeds = random(12)
// inspired by https://github.com/broofa/node-uuid/blob/v2.0.0/uuid.js#L362
seeds[5] = (seeds[5] & 0x0fff) | 0x4000 // version bits
seeds[7] = (seeds[7] & 0x3fff) | 0x8000 // clock_seq_hi_and_reserved bits
return 'xx-x-x-x-xxx'.replace(/x/g, function (x, index) { return hex(seeds[index]) })
function random (n) { // get n random 16-bit unsigned integers
var crypto = window.crypto || window.msCrypto
return crypto && window.Uint16Array ?
crypto.getRandomValues(new Uint16Array(n))
: Array.apply(null, Array(n)).map(() => Math.random() * 0xffff | 0)
}
function hex (integer) { // convert 16-bit integer to hexadecimal
return integer < 0x1000 ?
(integer + 0x10000).toString(16).substr(1) // keep leading zeros
: integer.toString(16)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.