Skip to content

Commit 4aeb347

Browse files
committed
fix: reject non-binary input in BinaryToHex
Invalid digits made hexLookup return undefined, and reversing the digits turned that into the string "denifednu".
1 parent 5c39e87 commit 4aeb347

2 files changed

Lines changed: 20 additions & 0 deletions

File tree

‎Conversions/BinaryToHex.js‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,14 @@ const hexLookup = (bin) => {
4444
}
4545
}
4646
const binaryToHex = (binaryString) => {
47+
if (typeof binaryString !== 'string') {
48+
throw new TypeError('Argument is not a string type')
49+
}
50+
51+
if (!/^[01]+$/.test(binaryString)) {
52+
throw new Error('Argument is not a valid binary string!')
53+
}
54+
4755
/*
4856
Function for converting Binary to Hex
4957

‎Conversions/test/BinaryToHex.test.js‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,16 @@ describe('BinaryToHex', () => {
1818
parseInt('1111', 2).toString(16).toUpperCase()
1919
)
2020
})
21+
22+
it('expects to throw for a non-string argument', () => {
23+
expect(() => binaryToHex(1000)).toThrowError()
24+
expect(() => binaryToHex(null)).toThrowError()
25+
})
26+
27+
it('expects to throw for a non-binary string', () => {
28+
expect(() => binaryToHex('2')).toThrowError()
29+
expect(() => binaryToHex('1002')).toThrowError()
30+
expect(() => binaryToHex('1010 1101')).toThrowError()
31+
expect(() => binaryToHex('')).toThrowError()
32+
})
2133
})

0 commit comments

Comments
 (0)