Skip to content

Instantly share code, notes, and snippets.

@outbreak
Created October 25, 2016 17:39
Show Gist options
  • Save outbreak/316637cde245160c2579898b21837c1c to your computer and use it in GitHub Desktop.
Save outbreak/316637cde245160c2579898b21837c1c 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);
}
@hareom284
Copy link

You can use crypto building into log

uuid crypto.randomUUID();

@outbreak
Copy link
Author

You can use crypto building into log

uuid crypto.randomUUID();

Yes, you're right. But five years ago there was no such thing. :)

Thanks

@henryroach
Copy link

uuid crypto.randomUUID() is not available in Safari

@hareom284
Copy link

@henryroach thank you so much >

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment