|
1 |
| -const binLookup = (c) => { |
2 |
| - switch (c.toLowerCase()) { |
3 |
| - case '0': return '0000' |
4 |
| - case '1': return '0001' |
5 |
| - case '2': return '0010' |
6 |
| - case '3': return '0011' |
7 |
| - case '4': return '0100' |
8 |
| - case '5': return '0101' |
9 |
| - case '6': return '0110' |
10 |
| - case '7': return '0111' |
11 |
| - case '8': return '1000' |
12 |
| - case '9': return '1001' |
13 |
| - case 'a': return '1010' |
14 |
| - case 'b': return '1011' |
15 |
| - case 'c': return '1100' |
16 |
| - case 'd': return '1101' |
17 |
| - case 'e': return '1110' |
18 |
| - case 'f': return '1111' |
19 |
| - default: return '' |
20 |
| - } |
21 |
| -} |
| 1 | +const binLookup = (key) => ({ |
| 2 | + 0: '0000', |
| 3 | + 1: '0001', |
| 4 | + 2: '0010', |
| 5 | + 3: '0011', |
| 6 | + 4: '0100', |
| 7 | + 5: '0101', |
| 8 | + 6: '0110', |
| 9 | + 7: '0111', |
| 10 | + 8: '1000', |
| 11 | + 9: '1001', |
| 12 | + a: '1010', |
| 13 | + b: '1011', |
| 14 | + c: '1100', |
| 15 | + d: '1101', |
| 16 | + e: '1110', |
| 17 | + f: '1111' |
| 18 | +}[key.toLowerCase()]) // select the binary number by valid hex key with the help javascript object |
| 19 | + |
22 | 20 | const hexToBinary = (hexString) => {
|
| 21 | + if (typeof hexString !== 'string') { |
| 22 | + throw new TypeError('Argument is not a string type') |
| 23 | + } |
| 24 | + |
| 25 | + if (/[^\da-f]/gi.test(hexString)) { |
| 26 | + throw new Error('Argument is not a valid HEX code!') |
| 27 | + } |
23 | 28 | /*
|
24 | 29 | Function for converting Hex to Binary
|
25 | 30 |
|
26 | 31 | 1. We convert every hexadecimal bit to 4 binary bits
|
27 | 32 | 2. Conversion goes by searching in the lookup table
|
| 33 | + */ |
28 | 34 |
|
29 |
| - */ |
30 |
| - const hexLexemes = hexString.split('') |
31 |
| - return hexLexemes.map(lexeme => binLookup(lexeme)).join('') |
| 35 | + return hexString.replace( |
| 36 | + /[0-9a-f]/gi, |
| 37 | + lexeme => binLookup(lexeme) |
| 38 | + ) |
32 | 39 | }
|
33 | 40 |
|
34 | 41 | export default hexToBinary
|
0 commit comments