Skip to content

Commit 7153180

Browse files
committed
fix: reject non-binary input in BinaryToDecimal
Digits other than 0 and 1 were coerced into the place-value sum, so binaryToDecimal('2') returned 2 and binaryToDecimal('102') returned 6.
1 parent 5c39e87 commit 7153180

2 files changed

Lines changed: 19 additions & 0 deletions

File tree

‎Conversions/BinaryToDecimal.js‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
11
export default function binaryToDecimal(binaryString) {
2+
if (typeof binaryString !== 'string') {
3+
throw new TypeError('Argument is not a string type')
4+
}
5+
6+
if (!/^[01]+$/.test(binaryString)) {
7+
throw new Error('Argument is not a valid binary string!')
8+
}
9+
210
let decimalNumber = 0
311
const binaryDigits = binaryString.split('').reverse() // Splits the binary number into reversed single digits
412
binaryDigits.forEach((binaryDigit, index) => {

‎Conversions/test/BinaryToDecimal.test.js‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,15 @@ describe('BinaryToDecimal', () => {
1212
it('expects to return correct hexadecimal value for padding-required binary', () => {
1313
expect(binaryToDecimal('1000101')).toBe(69)
1414
})
15+
16+
it('expects to throw for a non-string argument', () => {
17+
expect(() => binaryToDecimal(1000)).toThrowError()
18+
expect(() => binaryToDecimal(null)).toThrowError()
19+
})
20+
21+
it('expects to throw for a non-binary string', () => {
22+
expect(() => binaryToDecimal('2')).toThrowError()
23+
expect(() => binaryToDecimal('102')).toThrowError()
24+
expect(() => binaryToDecimal('')).toThrowError()
25+
})
1526
})

0 commit comments

Comments
 (0)