Created
April 8, 2024 21:32
-
-
Save maxsei/d3c66ae998f3d9d0de0c7bfefb0151ba to your computer and use it in GitHub Desktop.
uuid4 and maybe a valid uuid7 (aka tsid)
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
| const uuid4 = (): Uint8Array => { | |
| let res = crypto.getRandomValues(new Uint8Array(18)); | |
| res[6] = (res[6] & 0x0f) | 0x40; // Version 4 | |
| res[8] = (res[8] & 0x3f) | 0x80; // Variant is 10 | |
| return res | |
| }; | |
| const uuid7 = (() => { | |
| let prev = 0; | |
| return (): Uint8Array => { | |
| let res = uuid4(); | |
| let now = Date.now() * 1000000; | |
| if (now <= prev) { | |
| now = prev + 1; | |
| } | |
| prev = now; | |
| const t = now >> 12; | |
| const s = now & 0xfff; | |
| // Set time bits. | |
| res[0] = t >> 40; | |
| res[1] = t >> 32; | |
| res[2] = t >> 24; | |
| res[3] = t >> 16; | |
| res[4] = t >> 8; | |
| res[5] = t; | |
| res[6] = 0x70 | (0x0f & (s >> 8)); | |
| res[7] = s; | |
| return res | |
| }; | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment