Created
April 2, 2019 14:49
-
-
Save alenaksu/eb4285738590f618a0c537660ee955a4 to your computer and use it in GitHub Desktop.
UUIDv4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Generate a random UUIDv4 (rfc4122 compliant) | |
*/ | |
export function uuid(): string { | |
const uuid = [8, 4, 4, 4, 12].map((segmentLength: number) => { | |
let segment = Array(segmentLength); | |
for (let i = 0; i < segmentLength; i++) | |
// ToUint32 http://www.ecma-international.org/ecma-262/5.1/#sec-11.7.3 | |
segment[i] = (Math.random() * 0xf) >>> 0; | |
return segment; | |
}); | |
uuid[2][0] &= 0x3; | |
uuid[2][1] |= 0x8; | |
uuid[3][0] = 0x4; | |
return uuid | |
.map((segment: number[]) => segment.map(n => n.toString(16)).join('')) | |
.join('-'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment