UNPKG

@mhysko/s-uuid

Version:

Translate standard UUID to Base68 format and back

61 lines (60 loc) 1.81 kB
import { encodings } from './encodings.js'; class Converter { from; to; constructor(from = encodings.HEX, to = 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; } } export default Converter;