Skip to content

Commit 7ca1e46

Browse files
committed
fix: Throws errors for invalid base
1 parent 732e838 commit 7ca1e46

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

src/baseroo.test.ts

+21-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import * as assert from 'assert'
2-
import { convertBase, InvalidDigitError } from './baseroo'
2+
import { convertBase, defaultAlphabet, InvalidBaseError, InvalidDigitError } from './baseroo'
33

44
test('convertBase should convert base 16 to 10', () => {
55
const input = '8f'
@@ -29,3 +29,23 @@ test('convertBase should convert BigInts too', () => {
2929
const actualOutput = convertBase(interimOutput, 10, 16)
3030
assert.strictEqual(actualOutput, input)
3131
})
32+
33+
test('constrain should error for invalid fromBase', () => {
34+
const input = '8f'
35+
assert.throws(() => {
36+
convertBase(input, 1, 10)
37+
}, InvalidBaseError)
38+
assert.throws(() => {
39+
convertBase(input, defaultAlphabet.length + 1, 10)
40+
}, InvalidBaseError)
41+
})
42+
43+
test('constrain should error for invalid toBase', () => {
44+
const input = '8f'
45+
assert.throws(() => {
46+
convertBase(input, 16, 1)
47+
}, InvalidBaseError)
48+
assert.throws(() => {
49+
convertBase(input, 16, defaultAlphabet.length + 1)
50+
}, InvalidBaseError)
51+
})

src/baseroo.ts

+17-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@ export class InvalidDigitError extends BaseError {
66
}
77
}
88

9+
export class InvalidBaseError extends BaseError {
10+
constructor(public ref: string, public base: number, public maxBase: number) {
11+
super(`'${ref}' must be between 2 and ${maxBase} not '${base}'.`)
12+
}
13+
}
14+
915
function bigIntPow(x: bigint, y: bigint): bigint {
1016
const ZERO = BigInt(0)
1117
if (y === ZERO) return BigInt(1)
@@ -15,8 +21,18 @@ function bigIntPow(x: bigint, y: bigint): bigint {
1521
return x * p2 * p2
1622
}
1723

24+
export const defaultAlphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'
25+
1826
export function convertBase(value: string, fromBase: number, toBase: number): string {
19-
const range = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'.split('')
27+
const range = defaultAlphabet.split('')
28+
29+
if (fromBase < 2 || fromBase > range.length) {
30+
throw new InvalidBaseError('fromBase', fromBase, range.length)
31+
}
32+
if (toBase < 2 || toBase > range.length) {
33+
throw new InvalidBaseError('toBase', toBase, range.length)
34+
}
35+
2036
const fromRange = range.slice(0, fromBase)
2137
const toRange = range.slice(0, toBase)
2238

0 commit comments

Comments
 (0)