Skip to content

Instantly share code, notes, and snippets.

@dcts
Forked from outbreak/uuid.js
Created July 29, 2020 11:45
Show Gist options
  • Save dcts/a40e4ae321ed77e6a7fe6920d950bee0 to your computer and use it in GitHub Desktop.
Save dcts/a40e4ae321ed77e6a7fe6920d950bee0 to your computer and use it in GitHub Desktop.
UUID v4 JavaScript implementation with window.crypto.getRandomValues()
function uuid () {
function getRandomSymbol (symbol) {
var array;
if (symbol === 'y') {
array = ['8', '9', 'a', 'b'];
return array[Math.floor(Math.random() * array.length)];
}
array = new Uint8Array(1);
window.crypto.getRandomValues(array);
return (array[0] % 16).toString(16);
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, getRandomSymbol);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment