UNPKG

@thi.ng/ksuid

Version:

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

34 lines (33 loc) 737 B
import { AKSUID } from "./aksuid.js"; const MAX_EPOCH = -1 >>> 0; class KSUID32 extends AKSUID { constructor(opts) { super(4, { epoch: 16e11, bytes: 16, ...opts }); } timeOnlyBinary(epoch = Date.now(), buf) { buf = buf || new Uint8Array(this.size); const t = this.ensureTime((epoch - this.epoch) / 1e3, MAX_EPOCH) >>> 0; buf[0] = t >>> 24; buf[1] = t >> 16 & 255; buf[2] = t >> 8 & 255; buf[3] = t & 255; return buf; } parse(id) { const buf = this.tmp; this.base.decodeBytes(id, buf); return { epoch: this.u32(buf) * 1e3 + this.epoch, id: buf.slice(4) }; } } const defKSUID32 = (opts) => new KSUID32(opts); export { KSUID32, defKSUID32 };