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) => {
switch (c.toLowerCase()) {
case '0': return '0000'
case '1': return '0001'
case '2': return '0010'
case '3': return '0011'
case '4': return '0100'
case '5': return '0101'
case '6': return '0110'
case '7': return '0111'
case '8': return '1000'
case '9': return '1001'
case 'a': return '1010'
case 'b': return '1011'
case 'c': return '1100'
case 'd': return '1101'
case 'e': return '1110'
case 'f': return '1111'
default: return ''
}
}
const binLookup = (key) => ({
0: '0000',
1: '0001',
2: '0010',
3: '0011',
4: '0100',
5: '0101',
6: '0110',
7: '0111',
8: '1000',
9: '1001',
a: '1010',
b: '1011',
c: '1100',
d: '1101',
e: '1110',
f: '1111'
}[key.toLowerCase()]) // select the binary number by valid hex key with the help javascript object
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
1. We convert every hexadecimal bit to 4 binary bits
2. Conversion goes by searching in the lookup table
*/
*/
const hexLexemes = hexString.split('')
return hexLexemes.map(lexeme => binLookup(lexeme)).join('')
return hexString.replace(
/[0-9a-f]/gi,
lexeme => binLookup(lexeme)
)
}
export default hexToBinary