Skip to content

Instantly share code, notes, and snippets.

@gabrieldewes
Last active February 3, 2017 17:06
Show Gist options
  • Save gabrieldewes/a0842ad2bc7d1abca71719d206edf04e to your computer and use it in GitHub Desktop.
Save gabrieldewes/a0842ad2bc7d1abca71719d206edf04e to your computer and use it in GitHub Desktop.
Simple and fast generation of RFC4122 UUIDs in Browser
/* Simple and fast generation of RFC4122 UUIDS. */
(function(root, factory) {
'use strict';
root.uuid = factory();
})(window, function() {
var byteToHex = [];
for (var i=0; i<256; ++i) {
byteToHex[i] = (i + 0x100).toString(16).substr(1);
}
/* It's not a cryptographically strong random number generation.
* Unique ID creation requires a high quality random # generator. In the
* browser this is a little complicated due to unknown quality of Math.random().
* It's fast, but is of unspecified quality, and is better to use crypto libs.
*/
var rng = function() {
var rnds = new Array(16);
for (var i=0, r; i<16; i++) {
if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
}
return rnds;
};
function bytesToUuid(buf) {
var i = 0;
bth = byteToHex;
return bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]];
}
function uuid() {
var rnds = rng();
rnds[6] = (rnds[6] & 0x0f) | 0x40;
rnds[8] = (rnds[8] & 0x3f) | 0x80;
return bytesToUuid(rnds);
}
return uuid;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment