Skip to content

Instantly share code, notes, and snippets.

@tomasdev
Last active February 26, 2018 04:50
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 tomasdev/4112fba2a649b78ec6683529c65a03c5 to your computer and use it in GitHub Desktop.
Save tomasdev/4112fba2a649b78ec6683529c65a03c5 to your computer and use it in GitHub Desktop.
JavaScript UUID Generation using RFC4122 v4 (Random)
// UPDATE: shorter, non RFC compatible, but safe enough version
function guid() {
const s4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}
// Based off https://github.com/kelektiv/node-uuid
function uuid_v4() {
// Step 1: Random Numbers Generator
// Math.random()-based (RNG) - It's fast, but is of unspecified quality.
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;
}
// Step 2: Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = (rnds[6] & 0x0f) | 0x40;
rnds[8] = (rnds[8] & 0x3f) | 0x80;
// Step 3: Convert bytes into a UUID string
var bth = [];
for (var i = 0; i < 256; ++i) {
bth[i] = (i + 0x100).toString(16).substr(1);
}
i = 0;
return bth[rnds[i++]] + bth[rnds[i++]] +
bth[rnds[i++]] + bth[rnds[i++]] + '-' +
bth[rnds[i++]] + bth[rnds[i++]] + '-' +
bth[rnds[i++]] + bth[rnds[i++]] + '-' +
bth[rnds[i++]] + bth[rnds[i++]] + '-' +
bth[rnds[i++]] + bth[rnds[i++]] +
bth[rnds[i++]] + bth[rnds[i++]] +
bth[rnds[i++]] + bth[rnds[i++]];
}
function uuid_v4(){for(var r,n=new Array(16),t=0;t<16;t++)0==(3&t)&&(r=4294967296*Math.random()),n[t]=r>>>((3&t)<<3)&255;n[6]=15&n[6]|64,n[8]=63&n[8]|128;var a=[];for(t=0;t<256;++t)a[t]=(t+256).toString(16).substr(1);return t=0,a[n[t++]]+a[n[t++]]+a[n[t++]]+a[n[t++]]+"-"+a[n[t++]]+a[n[t++]]+"-"+a[n[t++]]+a[n[t++]]+"-"+a[n[t++]]+a[n[t++]]+"-"+a[n[t++]]+a[n[t++]]+a[n[t++]]+a[n[t++]]+a[n[t++]]+a[n[t++]]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment