Last active
June 20, 2024 02:51
-
-
Save snehesht/386f252d3fc7af40dfb26f3036d11fbc to your computer and use it in GitHub Desktop.
UUID v7
This file contains 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
// https://antonz.org/uuidv7/#javascript | |
export function uuidv7(): string { | |
// random bytes | |
const value = new Uint8Array(16); | |
crypto.getRandomValues(value); | |
// current timestamp in ms | |
const timestamp = BigInt(Date.now()); | |
// timestamp | |
value[0] = Number((timestamp >> 40n) & 0xffn); | |
value[1] = Number((timestamp >> 32n) & 0xffn); | |
value[2] = Number((timestamp >> 24n) & 0xffn); | |
value[3] = Number((timestamp >> 16n) & 0xffn); | |
value[4] = Number((timestamp >> 8n) & 0xffn); | |
value[5] = Number(timestamp & 0xffn); | |
// version and variant | |
value[6] = (value[6] & 0x0f) | 0x70; | |
value[8] = (value[8] & 0x3f) | 0x80; | |
return Array.from(value) | |
.map((b) => b.toString(16).padStart(2, "0")) | |
.reduce((a, b, idx) => { | |
if ([4, 6, 8, 10].includes(idx)) { | |
return a + "-" + b; | |
} | |
return a + b; | |
}); | |
} | |
console.log(uuidv7()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment