Skip to content

Commit

Permalink
alphabet: add back support for array of strings
Browse files Browse the repository at this point in the history
  • Loading branch information
paulmillr committed Nov 22, 2024
1 parent 860f890 commit 3dff1df
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
9 changes: 6 additions & 3 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,14 @@ function chain<T extends Chain & AsChain<T>>(...args: T): Coder<Input<First<T>>,
}

/**
* Encodes integer radix representation to array of strings using alphabet and back
* Encodes integer radix representation to array of strings using alphabet and back.
* Could also be array of strings.
*/
function alphabet(letters: string): Coder<number[], string[]> {
if (typeof letters !== 'string') throw new Error('invalid alphabet');
const indexes = Object.fromEntries(letters.split('').map((l, i) => [l, i]));
const lettersArr = typeof letters === 'string' ? letters.split('') : letters;
if (!isArrayOf('string', lettersArr))
throw new Error('alphabet expects string or array of strings');
const indexes = Object.fromEntries(lettersArr.map((l, i) => [l, i]));
return {
encode: (digits: number[]) => {
if (!isArrayOf('number', digits))
Expand Down
4 changes: 4 additions & 0 deletions test/bases.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,10 @@ should('utils: radix', () => {

should('utils: alphabet', () => {
const a = utils.alphabet('12345');
const ab = utils.alphabet(['11', '2', '3', '4', '5']);
assert.deepStrictEqual(a.encode([1]), ['2']);
assert.deepStrictEqual(ab.encode([0]), ['11']);
assert.deepStrictEqual(a.encode([2]), ab.encode([2]));
assert.throws(() => a.encode([1, 2, true, 3]));
assert.throws(() => a.decode(['1', 2, true]));
assert.throws(() => a.decode(['1', 2]));
Expand Down

0 comments on commit 3dff1df

Please sign in to comment.