Skip to content

Instantly share code, notes, and snippets.

@ali-master
Created July 15, 2024 19:49
Show Gist options
  • Save ali-master/e5e527944d7e2b010636a6f5b3321d95 to your computer and use it in GitHub Desktop.
Save ali-master/e5e527944d7e2b010636a6f5b3321d95 to your computer and use it in GitHub Desktop.
UUIDv7 in typescript

UUIDv7 is a 128-bit unique identifier like it's older siblings, such as the widely used UUIDv4. But unlike v4, UUIDv7 is time-sortable with 1 ms precision. By combining the timestamp and the random parts, UUIDv7 becomes an excellent choice for record identifiers in databases, including distributed ones.

Let's briefly explore the UUIDv7 structure and move on to the zero-dependency implementations in 33 languages (as ranked by the Stack Overflow survey).

These implementations may not be the fastest or most idiomatic, but they are concise and easy to understand. Many of the code examples are interactive (but the results are cached, so you won't see different UUIDs very often).

function uuidv7(): Uint8Array {
/**
* Initialize a random array with crypto.getRandomValues(), get the current timestamp with Date.now(),
* fill the array from the timestamp, set version and variant.
*/
// 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 value;
}
const uuidVal = uuidv7();
const uuidStr = Array.from(uuidVal)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
console.log(uuidStr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment