Skip to content

Commit

Permalink
perf(base-n): memoize value padding (encoding w/ size)
Browse files Browse the repository at this point in the history
- migrate padding into BaseN class
- add BaseN.clear() for clearing memoization cache
  • Loading branch information
postspectacular committed Jan 26, 2024
1 parent 5d39cda commit 62ccf80
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions packages/base-n/src/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export class BaseN implements IBase {
readonly N: number;
readonly index: Record<string, number>;

private __pc: string[] = [];

constructor(public readonly base: string) {
this.N = base.length;
this.index = [...base].reduce(
Expand All @@ -22,28 +24,32 @@ export class BaseN implements IBase {
);
}

clear() {
this.__pc.length = 0;
}

encode(x: number, size = 0) {
const { base, N } = this;
if (x === 0) return __pad(base[0], size, base[0]);
if (x === 0) return this.__pad(base[0], size);
let res = "";
while (x > 0) {
res = base[x % N] + res;
x = Math.floor(x / N);
}
return __pad(res, size, base[0]);
return this.__pad(res, size);
}

encodeBigInt(x: bigint, size = 0) {
if (x <= MAX_SAFE_INT) return this.encode(Number(x), size);
const { base, N } = this;
if (x === ZERO) return __pad(base[0], size, base[0]);
if (x === ZERO) return this.__pad(base[0], size);
const NN = BigInt(N);
let res = "";
while (x > ZERO) {
res = base[Number(x % NN)] + res;
x /= NN;
}
return __pad(res, size, base[0]);
return this.__pad(res, size);
}

encodeBytes(buf: Uint8Array, size = 0) {
Expand Down Expand Up @@ -87,13 +93,14 @@ export class BaseN implements IBase {
size(x: number) {
return Math.ceil(Math.log(x) / Math.log(this.N));
}
}

/** @internal */
const __pad = (x: string, size: number, fill: string) => {
const d = size - x.length;
return d > 0 ? fill.repeat(d) + x : x;
};
private __pad(x: string, size: number) {
const d = size - x.length;
return d > 0
? (this.__pc[d] || (this.__pc[d] = this.base[0].repeat(d))) + x
: x;
}
}

/** @internal */
const __u8 = (x: number) =>
Expand Down

0 comments on commit 62ccf80

Please sign in to comment.