UUID Class
Projects | | Links: Site | Source
A minimal UUID class for JavaScript. UUIDs are represented as bytes (Uint8Array
) and converted to strings on-demand.
I’ve built the UUID class that I felt was missing form JavaScript.
As I’ve been dealing with binary data in JavaScript more and more, it has only became natural to expect UUIDs — which are essentially 128 bits to data — to be represented in JS’ native binary data type, ArrayBuffer
.
While other libraries represent UUIDs as strings, this one keeps the bits in an ArrayBuffer
and converts to strings when/where needed, such as console logging and stringification.
Other times, a string-conversion isn’t required, such as when using UUID as keys in an IndexedDB, e.g.
await new StorageArea('foobar').put(new UUID(), { some: 'data' })
Example
Together with Base64 Encoding this enables creating short, URL-friendly UUIDs:
For example the following strings represents the same 128 bit of data:
ed672cd6-696b-4d22-a977-f3442da10c1d <=> 7Wcs1mlrTSKpd_NELaEMHQ
Converting between the two works as follows:
const id = new UUID('ed672cd6-696b-4d22-a977-f3442da10c1d')
new Base64Encoder({ url: true }).encode(id)
// => 7Wcs1mlrTSKpd_NELaEMHQ
new UUID(new Base64Decoder().decode('7Wcs1mlrTSKpd_NELaEMHQ'))
// => UUID [ ed672cd6-696b-4d22-a977-f3442da10c1d ]