Skip to content

Instantly share code, notes, and snippets.

@mlhaufe
Created June 30, 2024 17:37
Show Gist options
  • Save mlhaufe/322ff76955ce1426e850df87e62432c9 to your computer and use it in GitHub Desktop.
Save mlhaufe/322ff76955ce1426e850df87e62432c9 to your computer and use it in GitHub Desktop.
Create uuid7()
function xuuid7(): string {
const randomUUID = crypto.randomUUID();
const randomUUIDArray = uuidToBytes(randomUUID);
// Get the current timestamp in milliseconds
const timestamp = Math.floor(Date.now());
// Convert the timestamp to a byte array
const timestampBytes = new Uint8Array(8);
const timestampView = new DataView(timestampBytes.buffer);
timestampView.setBigInt64(0, BigInt(timestamp));
// Overlay the timestamp into the UUID
for (let i = 0; i < 6; i++) {
randomUUIDArray[i] = timestampBytes[i + 2];
}
// Set version 7 by flipping the 2nd and 1st bits in the 7th byte
randomUUIDArray[6] = (randomUUIDArray[6] & 0x0f) | 0x70;
// Set the variant to RFC 4122 (which is 10xx in binary)
randomUUIDArray[8] = (randomUUIDArray[8] & 0x3f) | 0x80;
return bytesToUUID(randomUUIDArray);
}
function uuidToBytes(uuid: string): Uint8Array {
return Uint8Array.from(uuid.match(/[\da-f]{2}/gi)!.map((h) => parseInt(h, 16)));
}
function bytesToUUID(bytes: Uint8Array): string {
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
}
console.log(xuuid7());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment