From 08087e921ede553d1eaeb682d264c3d4c217a3cd Mon Sep 17 00:00:00 2001 From: Nimalan Date: Wed, 11 Sep 2019 22:04:44 +0530 Subject: [PATCH] Make uuid v4 rfc4122 compliant (denoland/deno_std#580) Original: https://github.com/denoland/deno_std/commit/ba69f1ea143a3a90e146e71c12c3ae65341373c3 --- uuid/v4.ts | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/uuid/v4.ts b/uuid/v4.ts index eeb9c4f140396a..84ba28b0f5d88c 100644 --- a/uuid/v4.ts +++ b/uuid/v4.ts @@ -10,10 +10,26 @@ export function validate(id: string): boolean { } export default function generate(): string { - return "00000000-0000-4000-8000-000000000000".replace( - /[0]/g, - (): string => - // random integer from 0 to 15 as a hex digit. - (crypto.getRandomValues(new Uint8Array(1))[0] % 16).toString(16) + const rnds = crypto.getRandomValues(new Uint8Array(16)); + + rnds[6] = (rnds[6] & 0x0f) | 0x40; // Version 4 + rnds[8] = (rnds[8] & 0x3f) | 0x80; // Variant 10 + + const bits: string[] = [...rnds].map( + (bit): string => { + const s: string = bit.toString(16); + return bit < 0x10 ? "0" + s : s; + } ); + return [ + ...bits.slice(0, 4), + "-", + ...bits.slice(4, 6), + "-", + ...bits.slice(6, 8), + "-", + ...bits.slice(8, 10), + "-", + ...bits.slice(10) + ].join(""); }