Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support custom alphabet #421

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 9 additions & 6 deletions src/baseroo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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)
}
Expand All @@ -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)