Skip to content

Instantly share code, notes, and snippets.

@gf3
Created December 19, 2016 16:37
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save gf3/ce467caacf692e323fc22a729939dd8e to your computer and use it in GitHub Desktop.
UUIDs ES6
/**
* Convert a number or array of integers to a string of padded hex octets.
*/
function asHex(value: Array<number> | Uint8Array): string {
return Array.from(value).map(i => ('00' + i.toString(16)).slice(-2)).join('');
}
/**
* Attempt to securely generate random bytes/
*/
function getRandomBytes(size: number): Array<number> | Uint8Array {
// SPRNG
if ((typeof Uint8Array == 'function') && window.crypto) {
let buffer = new Uint8Array(size);
return window.crypto.getRandomValues(buffer);
}
// Insecure random
return Array.from(new Array(size), () => Math.random() * 255 | 0);
}
/**
* Generate a RFC4122-compliant v4 UUID.
*
* @see http://www.ietf.org/rfc/rfc4122.txt
*/
export function generateUuid(): string {
const version = 0b01000000;
const clockSeqHiAndReserved = getRandomBytes(1);
const timeHiAndVersion = getRandomBytes(2);
clockSeqHiAndReserved[0] &= 0b00111111 | 0b10000000;
timeHiAndVersion[0] &= 0b00001111 | version;
return [
asHex(getRandomBytes(4)), // time-low
'-',
asHex(getRandomBytes(2)), // time-mid
'-',
asHex(timeHiAndVersion), // time-high-and-version
'-',
asHex(clockSeqHiAndReserved), // clock-seq-and-reserved
asHex(getRandomBytes(1)), // clock-seq-loq
'-',
asHex(getRandomBytes(6)) // node
].join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment