UNPKG

@digitalmaas/uuid-base62

Version:
66 lines (63 loc) 1.95 kB
// lib/index.ts import baseX from "base-x"; // lib/helpers.ts function trimLeft(target, length) { target = String(target); let trim = 0; while (target[trim] === "0" && target.length - trim > length) trim++; return target.slice(trim); } function ensureLength(target, length) { target = String(target); if (target.length < length) { return target.padStart(length, "0"); } if (target.length > length) { return trimLeft(target, length); } return target; } // lib/index.ts var base62Alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; var UUID_LENGTH = 36; var UUID_NO_DASH = UUID_LENGTH - 4; var ID_LENGTH = 22; var base62 = baseX(base62Alphabet); function encode(input, options) { if (!(typeof input === "string" && input.length === UUID_LENGTH || Buffer.isBuffer(input))) { throw new TypeError("encode input is not a valid uuid"); } options = options || {}; const encoding = options.encoding || "hex"; const base = options.base || base62; if (typeof input === "string") { input = Buffer.from(input.replace(/-/g, ""), encoding); } const output = base.encode(input); const length = options.length === false ? false : options.length || ID_LENGTH; return length ? ensureLength(output, length) : output; } function decode(input, options) { if (!(typeof input === "string" && input.length > 0)) { throw new TypeError("decode input is not valid"); } options = options || {}; const encoding = options.encoding || "hex"; const base = options.base || base62; const length = options.length || UUID_NO_DASH; let decoded = Buffer.from(base.decode(input)).toString(encoding); decoded = ensureLength(decoded, length); const chars = decoded.split(""); chars.splice(8, 0, "-"); chars.splice(13, 0, "-"); chars.splice(18, 0, "-"); chars.splice(23, 0, "-"); return chars.join(""); } export { base62, base62Alphabet, baseX, decode, encode };