UUID Class

UUID Class

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' })

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({ urlFriendly: true }).encode(id.buffer)
// => 7Wcs1mlrTSKpd_NELaEMHQ

new UUID(new Base64Decoder().decode('7Wcs1mlrTSKpd_NELaEMHQ'))
// => UUID [ ed672cd6-696b-4d22-a977-f3442da10c1d ]

© 2020. All rights reserved.

Powered by Hydejack v9.1.0-beta.1