13 lines
519 B
TypeScript
13 lines
519 B
TypeScript
const hexdigit = (c: number) => '0123456789abcdef'[c & 15];
|
|
export function uuid(): string {
|
|
// https://datatracker.ietf.org/doc/html/rfc4122#section-4.4
|
|
const bs = new Uint8Array(16);
|
|
crypto.getRandomValues(bs);
|
|
bs[6] = (bs[6] & 15) | 0x40;
|
|
bs[8] = (bs[8] & 63) | 0x80;
|
|
const result: string[] = [];
|
|
bs.forEach(b => result.push(hexdigit(b >> 4), hexdigit(b)));
|
|
const s = result.join('');
|
|
return [s.slice(0,8), s.slice(8,12), s.slice(12,16), s.slice(16,20), s.slice(20)].join('-');
|
|
}
|