How to Create a Guid/UUID
at code.askmein.com▼1 up and 1 down, posted by
1 up and 1 down, posted by
Regarding the use of Math.random()
function createUUID() {
const fmt = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
const rnd = Array.from(crypto.getRandomValues(new Uint8Array(32)))
.map(n => n&0xf);
const rk = (c,r) => ((c == 'x' ? r : (r&0x3|0x8)).toString(16));
return fmt.replace(/[xy]/g, c => rk(c, rnd.pop()));
}
[0] https://caniuse.com/#feat=cryptography
[1] https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
IE11 support... function createUUID() { var fmt = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'; var rnd = Array.from((window.crypto || window.msCrypto).getRandomValues(new Uint8Array(32))).map(function(n){ return n&0xf }); function rk(c,r) {return (c == 'x' ? r : (r&0x3|0x8)).toString(16); }; return fmt.replace(/[xy]/g, function(c) { return rk(c, rnd.pop()); }); }NodeJS support... const crypto = require("crypto"); function createUUID() { const fmt = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"; const rnd = Array.from(crypto.randomBytes(32)).map(n => n & 0xf); const rk = (c, r) => (c == "x" ? r : (r & 0x3) | 0x8).toString(16); return fmt.replace(/[xy]/g, c => rk(c, rnd.pop())); }