Last active
November 14, 2025 04:21
-
-
Save atoponce/cdba60bc83bc0df23dc1f067eccd5d58 to your computer and use it in GitHub Desktop.
Very efficient type 4 UUID generator in vanilla JavaScript. Runs in ~7.81 cpb on an Intel Core i7-8650U @ 1.9 GHz.
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 uuid = new UUID(); | |
| console.log(uuid.v4()); |
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
| // Do not use for security. Use crypto.randomUUID() instead. | |
| class UUID { | |
| #hex = []; | |
| constructor() { | |
| for (let i = 0; i < 0x10000; i++) { | |
| this.#hex[i] = i.toString(16).padStart(4, "0"); | |
| } | |
| } | |
| v4() { | |
| const r1 = Math.random() * 0x100000000 >>> 0; | |
| const r2 = Math.random() * 0x100000000 >>> 0; | |
| const r3 = Math.random() * 0x100000000 >>> 0; | |
| const r4 = Math.random() * 0x100000000 >>> 0; | |
| return this.#hex[r1 >>> 16] + this.#hex[r1 & 0xffff] + "-" +// xxxxxxxx-....-4...-y...-............ | |
| this.#hex[r2 >>> 16] + "-" + // ........-xxxx-4...-y...-............ | |
| this.#hex[r2 & 0x0fff | 0x4000] + "-" + // ........-....-4xxx-y...-............ | |
| this.#hex[r3 >>> 16 & 0x3fff | 0x8000] + "-" + // ........-....-4...-yxxx-............ | |
| this.#hex[r3 & 0xffff] + // ........-....-4...-y...-xxxx........ | |
| this.#hex[r4 >>> 16] + this.#hex[r4 & 0xffff]; // ........-....-4...-y...-....xxxxxxxx | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment