Skip to content

Instantly share code, notes, and snippets.

@snehesht
Last active June 20, 2024 02:51
Show Gist options
  • Save snehesht/386f252d3fc7af40dfb26f3036d11fbc to your computer and use it in GitHub Desktop.
Save snehesht/386f252d3fc7af40dfb26f3036d11fbc to your computer and use it in GitHub Desktop.
UUID v7
// 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