Skip to content

Instantly share code, notes, and snippets.

@qubyte
Last active August 29, 2015 14:17
Show Gist options
  • Save qubyte/be8e75a75568fa800979 to your computer and use it in GitHub Desktop.
Save qubyte/be8e75a75568fa800979 to your computer and use it in GitHub Desktop.
UUID version 4 using browser crypto API. Not particularly optimised.
function makeUuid(){
var randomValues = window.crypto.getRandomValues(new window.Uint8ClampedArray(16));
var randomHex = '';
for (var i = 0; i < randomValues.length - 1; i++) {
var hex = randomValues[i].toString(16);
if (hex.length === 0) {
randomHex += '00';
} else if (hex.length === 1) {
randomHex += '0' + hex;
} else {
randomHex += hex;
}
}
var special;
if (randomValues[15] < 64) {
special = '8';
} else if (randomValues[15] < 128) {
special = '9';
} else if (randomValues[15] < 192) {
special = 'A';
} else {
special = 'B';
}
return [
randomHex.slice(0, 8),
randomHex.slice(8, 12),
'4' + randomHex.slice(12, 15),
special + randomHex.slice(15, 18),
randomHex.slice(18, 30)
].join('-');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment