@digitalmaas/uuid-base62
Version:
Base62 UUID encoder and decoder
66 lines (57 loc) • 2.27 kB
JavaScript
;Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// lib/index.ts
var _basex = require('base-x'); var _basex2 = _interopRequireDefault(_basex);
// 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 = _basex2.default.call(void 0, 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("");
}
exports.base62 = base62; exports.base62Alphabet = base62Alphabet; exports.baseX = _basex2.default; exports.decode = decode; exports.encode = encode;