Skip to content

Commit d19258f

Browse files
committed
perf: use Int8Array instead of Map in alphabet.decode
1 parent e95be95 commit d19258f

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

index.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,12 @@ function alphabet(letters: string | string[]): Coder<Uint8Array, string[]> {
9191
astrArr('alphabet', lettersA);
9292

9393
// mapping "b" to 1
94-
const indexes = new Map(lettersA.map((l, i) => [l, i]));
94+
const indexes = new Int8Array(256).fill(-1);
95+
lettersA.forEach((l, i) => {
96+
const code = l.codePointAt(0)!;
97+
if (code > 127 || indexes[code] !== -1) throw new Error(`Non-ascii or duplicate symbol: "${l}"`);
98+
indexes[code] = i;
99+
});
95100
return {
96101
encode: (digits: Uint8Array): string[] => {
97102
abytes(digits);
@@ -111,8 +116,9 @@ function alphabet(letters: string | string[]): Coder<Uint8Array, string[]> {
111116
let at = 0
112117
for (const letter of input) {
113118
astr('alphabet.decode', letter);
114-
const i = indexes.get(letter);
115-
if (i === undefined) throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
119+
const c = letter.codePointAt(0)!;
120+
const i = indexes[c]!;
121+
if (letter.length !== 1 || c > 256 || i < 0) throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
116122
out[at++] = i;
117123
}
118124
return out;

0 commit comments

Comments
 (0)