diff options
author | Lucas Caro <lucascaro@gmail.com> | 2019-07-03 08:13:22 -0700 |
---|---|---|
committer | Ryan Dahl <ry@tinyclouds.org> | 2019-07-03 11:13:22 -0400 |
commit | 6a0858bd5d9d327ac7f46bee5f5b2fab642f2a3f (patch) | |
tree | 1459f0757fd5ac9bfe3c3a650606f7cd8f4ac848 /uuid/v4.ts | |
parent | 78a9a27e6fcecdac9a11cb01adf585feceed9e18 (diff) |
add UUID module (denoland/deno_std#479)
Original: https://github.com/denoland/deno_std/commit/f52b3ec002ac38aa9146695283aa491bc2d115b6
Diffstat (limited to 'uuid/v4.ts')
-rw-r--r-- | uuid/v4.ts | 19 |
1 files changed, 19 insertions, 0 deletions
diff --git a/uuid/v4.ts b/uuid/v4.ts new file mode 100644 index 000000000..eeb9c4f14 --- /dev/null +++ b/uuid/v4.ts @@ -0,0 +1,19 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. + +const UUID_RE = new RegExp( + "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "i" +); + +export function validate(id: string): boolean { + return UUID_RE.test(id); +} + +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) + ); +} |