@mhysko/s-uuid
Version:
Translate standard UUID to Base68 format and back
63 lines (62 loc) • 1.92 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const encodings_js_1 = require("./encodings.js");
class Converter {
from;
to;
constructor(from = encodings_js_1.encodings.HEX, to = encodings_js_1.encodings.BASE58) {
this.from = from;
this.to = to;
}
encode(input) {
return this.#convert(input, this.from, this.to);
}
decode(input) {
return this.#convert(input, this.to, this.from);
}
#convert(input, from, to) {
if (!this.#validate(input, from)) {
throw new Error(`Input ${input} contains invalid characters. Expected only ${from}`);
}
if (from === to) {
return input;
}
const map = new Map();
let inLength = input.length;
let outLength;
let i = 0;
for (i = 0; i < inLength; i++) {
map.set(i, from.indexOf(input[i]));
}
const toLength = to.length;
const fromLength = from.length;
let divide;
let result = '';
do {
divide = 0;
outLength = 0;
for (i = 0; i < inLength; i++) {
divide = divide * fromLength + (map.get(i) ?? 0);
if (divide >= toLength) {
map.set(outLength++, parseInt((divide / toLength).toString(), 10));
divide = divide % toLength;
}
else if (outLength > 0) {
map.set(outLength++, 0);
}
}
inLength = outLength;
result = to.slice(divide, divide + 1).concat(result);
} while (outLength !== 0);
return result;
}
#validate(input, from) {
for (const char of input) {
if (!from.includes(char)) {
return false;
}
}
return true;
}
}
exports.default = Converter;