UNPKG

@thi.ng/ksuid

Version:

Configurable K-sortable unique IDs, ULIDs, binary & base-N encoded, 32/48/64bit time resolutions

41 lines (40 loc) 897 B
import { BASE32_CROCKFORD } from "@thi.ng/base-n/32"; import { AKSUID } from "./aksuid.js"; class ULID extends AKSUID { constructor(opts) { super(6, { epoch: 0, bytes: 10, base: BASE32_CROCKFORD, ...opts }); } timeOnlyBinary(epoch = Date.now()) { const buf = new Uint8Array(this.size); const t = this.ensureTime(epoch - this.epoch); const h = t / 4294967296 >>> 0; const l = (t & 4294967295) >>> 0; buf.set([ h >> 8 & 255, h & 255, l >>> 24, l >> 16 & 255, l >> 8 & 255, l & 255 ]); return buf; } parse(id) { const buf = new Uint8Array(this.size); this.base.decodeBytes(id, buf); return { epoch: (buf[0] << 8 | buf[1]) * 4294967296 + this.u32(buf, 2) + this.epoch, id: buf.slice(6) }; } } const defULID = (opts) => new ULID(opts); export { ULID, defULID };