@thi.ng/base-n
Version:
Arbitrary base-n conversions w/ presets for base8/16/32/36/58/62/64/83/85, support for bigints and encoding/decoding of byte arrays
44 lines (43 loc) • 888 B
JavaScript
class BaseNDecoder {
constructor(base) {
this.base = base;
this.N = base.length;
this.index = [...base].reduce(
(acc, x, i) => (acc[x] = i, acc),
{}
);
}
N;
index;
decode(x) {
const { index, N } = this;
let res = 0;
for (let n = x.length - 1, i = 0; i <= n; i++) {
res += index[x[i]] * N ** (n - i);
}
return res;
}
decodeBigInt(x) {
const { index, N } = this;
const NN = BigInt(N);
let res = 0n;
for (let n = x.length - 1, i = 0; i <= n; i++) {
res += BigInt(index[x[i]]) * NN ** BigInt(n - i);
}
return res;
}
decodeBytes(x, buf) {
let y = this.decodeBigInt(x);
for (let i = buf.length; i-- > 0; ) {
buf[i] = Number(y & 255n);
y >>= 8n;
}
return buf;
}
validate(x) {
return new RegExp(`^[${this.base}]+$`).test(x);
}
}
export {
BaseNDecoder
};