diff --git a/Conversions/HexToBinary.js b/Conversions/HexToBinary.js index 2334954f9..2456dba01 100644 --- a/Conversions/HexToBinary.js +++ b/Conversions/HexToBinary.js @@ -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 diff --git a/Conversions/test/HexToBinary.test.js b/Conversions/test/HexToBinary.test.js index 40148d1ce..6a7ec265d 100644 --- a/Conversions/test/HexToBinary.test.js +++ b/Conversions/test/HexToBinary.test.js @@ -1,6 +1,18 @@ 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', () => { expect(hexToBinary('8')).toBe('1000') })