| 3 | 3 | // convenience to get you started writing code faster. |
| 4 | 4 | // |
| 5 | 5 | |
| 6 | | export const convert = () => { |
| 7 | | throw new Error('Remove this line and implement the function'); |
| 6 | export const convert = (digits, fromBase, toBase) => { |
| 7 | // Edge Case: Invalid base (less than 2) |
| 8 | if (fromBase < 2 || !Number.isInteger(fromBase)) { |
| 9 | throw new Error('Wrong input base'); |
| 10 | } |
| 11 | |
| 12 | // Edge Case: Invalid base (less than 2) |
| 13 | if (toBase < 2 || !Number.isInteger(toBase)) { |
| 14 | throw new Error('Wrong output base'); |
| 15 | } |
| 16 | |
| 17 | // Edge Case: Empty digits array |
| 18 | if (digits.length === 0) { |
| 19 | throw new Error('Input has wrong format'); |
| 20 | } |
| 21 | |
| 22 | // Edge Case: Leading zero in multi-digit number |
| 23 | if (digits.length > 1 && digits[0] === 0) { |
| 24 | throw new Error('Input has wrong format'); |
| 25 | } |
| 26 | |
| 27 | // Edge Case: Invalid digits for the given base |
| 28 | for (let digit of digits) { |
| 29 | if (digit < 0 || digit >= fromBase || !Number.isInteger(digit)) { |
| 30 | throw new Error('Input has wrong format'); |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | // Convert from source base to decimal |
| 35 | let decimalValue = 0; |
| 36 | for (let i = 0; i < digits.length; i++) { |
| 37 | decimalValue = decimalValue * fromBase + digits[i]; |
| 38 | } |
| 39 | |
| 40 | // Edge Case: Zero conversion |
| 41 | if (decimalValue === 0) { |
| 42 | return [0]; |
| 43 | } |
| 44 | |
| 45 | // Convert from decimal to target base |
| 46 | const result = []; |
| 47 | while (decimalValue > 0) { |
| 48 | result.unshift(decimalValue % toBase); |
| 49 | decimalValue = Math.floor(decimalValue / toBase); |
| 50 | } |
| 51 | |
| 52 | return result; |
| 8 | 53 | }; |
| 54 | |
| 55 | // Handled Edge Cases: Invalid base (less than 2), Empty digits array, Leading zero in multi-digit number, Invalid digits for the given base, Zero conversion |