diff --git a/readme.md b/readme.md index 2159fa03..548e9cf3 100644 --- a/readme.md +++ b/readme.md @@ -12,12 +12,18 @@ ```ts // Install it with `npm i baseroo` -import { convertBase } from 'baseroo' +import { convertBase, customAlphabet } from 'baseroo' const base16Value = '8f.3333333333' // Works for floating point numbers to a precision of 10 places. const base10Value = convertBase(base16Value, 16, 10) // '143.1999999999' + +// Supports base conversion using custom alphabet +const convertBaseWithUserAlphabet = customAlphabet( + '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/' +) +const base32Value = convertBase(base16Value, 16, 32) // '4f.6cpj6cpj' ``` ### Background diff --git a/src/baseroo.ts b/src/baseroo.ts index e4ff02de..e3defc08 100644 --- a/src/baseroo.ts +++ b/src/baseroo.ts @@ -23,9 +23,6 @@ function bigIntPow(x: bigint, y: bigint): bigint { return x * p2 * p2 } -export const defaultAlphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/' -const defaultAlphabetRange = defaultAlphabet.split('') - function convertToBase10Integer(integerValue: string, fromAlphabet: string[]): bigint { const fromBase = BigInt(fromAlphabet.length) @@ -76,9 +73,7 @@ function convertFromBase10Fractional(base10Fractional: number, toAlphabet: strin return value } -export function convertBase(value: string, fromBase: number, toBase: number): string { - const range = defaultAlphabetRange - +function convertBaseShim(range: string[], value: string, fromBase: number, toBase: number): string { if (fromBase < 2 || fromBase > range.length) { throw new InvalidBaseError('fromBase', fromBase, range.length) } @@ -104,3 +99,11 @@ export function convertBase(value: string, fromBase: number, toBase: number): st return toBaseSign + toBaseInteger } + +export function customAlphabet(alphabet: string) { + return convertBaseShim.bind(null, alphabet.split('')) +} + +export const defaultAlphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/' + +export const convertBase = customAlphabet(defaultAlphabet)