Zyzle.dev
;

Generate a Version 4 UUID

18th February, 2023

This typescript function generates a UUID using the RFC 4122 specification1.

Version 4 UUIDs take the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hex digit and y is in [8, 9, a, b].

Assuming these are generated with sufficient entropy, 1B UUIDs every second for 100 years would be ~50% chance of collision2

uuid.ts
function generateUUIDv4(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}

Footnotes

  1. Read the specification at RFC 4122

  2. Learn more about UUIDs at Wikipedia