merge: Upgraded hexToBinary function (#910)

* feat: used js object intead of switch

* pref: optimzed the algo with regex & replace method

* feat: add hex validation with test case

* feat: add type validation

* chore: fix grammar mistake

* docs: add binLookup comments
This commit is contained in:
Fahim Faisaal
2022-03-02 10:10:07 +06:00
committed by GitHub
parent ab06131656
commit 378d4abebc
2 changed files with 44 additions and 25 deletions

View File

@ -1,34 +1,41 @@
const binLookup = (c) => { const binLookup = (key) => ({
switch (c.toLowerCase()) { 0: '0000',
case '0': return '0000' 1: '0001',
case '1': return '0001' 2: '0010',
case '2': return '0010' 3: '0011',
case '3': return '0011' 4: '0100',
case '4': return '0100' 5: '0101',
case '5': return '0101' 6: '0110',
case '6': return '0110' 7: '0111',
case '7': return '0111' 8: '1000',
case '8': return '1000' 9: '1001',
case '9': return '1001' a: '1010',
case 'a': return '1010' b: '1011',
case 'b': return '1011' c: '1100',
case 'c': return '1100' d: '1101',
case 'd': return '1101' e: '1110',
case 'e': return '1110' f: '1111'
case 'f': return '1111' }[key.toLowerCase()]) // select the binary number by valid hex key with the help javascript object
default: return ''
}
}
const hexToBinary = (hexString) => { const hexToBinary = (hexString) => {
if (typeof hexString !== 'string') {
throw new TypeError('Argument is not a string type')
}
if (/[^\da-f]/gi.test(hexString)) {
throw new Error('Argument is not a valid HEX code!')
}
/* /*
Function for converting Hex to Binary Function for converting Hex to Binary
1. We convert every hexadecimal bit to 4 binary bits 1. We convert every hexadecimal bit to 4 binary bits
2. Conversion goes by searching in the lookup table 2. Conversion goes by searching in the lookup table
*/
*/ return hexString.replace(
const hexLexemes = hexString.split('') /[0-9a-f]/gi,
return hexLexemes.map(lexeme => binLookup(lexeme)).join('') lexeme => binLookup(lexeme)
)
} }
export default hexToBinary export default hexToBinary

View File

@ -1,6 +1,18 @@
import hexToBinary from '../HexToBinary' import hexToBinary from '../HexToBinary'
describe('hexToBinary', () => { describe('Testing hexToBinary', () => {
it('expects throw error in invalid types', () => {
expect(() => hexToBinary(false)).toThrowError()
expect(() => hexToBinary(null)).toThrowError()
expect(() => hexToBinary(23464)).toThrowError()
})
it('expects throw error in invalid hex', () => {
expect(() => hexToBinary('Hello i am not a valid Hex')).toThrowError()
expect(() => hexToBinary('Gf46f')).toThrowError()
expect(() => hexToBinary('M')).toThrowError()
})
it('expects to return correct hexadecimal value', () => { it('expects to return correct hexadecimal value', () => {
expect(hexToBinary('8')).toBe('1000') expect(hexToBinary('8')).toBe('1000')
}) })