| 9 | 9 | * @param {number} outputBase |
| 10 | 10 | */ |
| 11 | 11 | export const convert = (array, inputBase, outputBase) => { |
| 12 | | throw new Error('Remove this line and implement the function'); |
| 12 | // Edge Case: Invalid input base (less than 2) |
| 13 | if (inputBase < 2 || !Number.isInteger(inputBase)) { |
| 14 | throw new Error('Wrong input base'); |
| 15 | } |
| 16 | |
| 17 | // Edge Case: Invalid output base (less than 2) |
| 18 | if (outputBase < 2 || !Number.isInteger(outputBase)) { |
| 19 | throw new Error('Wrong output base'); |
| 20 | } |
| 21 | |
| 22 | // Edge Case: Empty input array |
| 23 | if (array.length === 0) { |
| 24 | throw new Error('Input has wrong format'); |
| 25 | } |
| 26 | |
| 27 | // Edge Case: Single digit input being zero |
| 28 | if (array.length === 1 && array[0] === 0) { |
| 29 | return [0]; |
| 30 | } |
| 31 | |
| 32 | // Edge Case: Leading zeros in multi-digit number |
| 33 | if (array.length > 1 && array[0] === 0) { |
| 34 | throw new Error('Input has wrong format'); |
| 35 | } |
| 36 | |
| 37 | // Edge Case: Negative digits |
| 38 | for (let digit of array) { |
| 39 | if (digit < 0) { |
| 40 | throw new Error('Input has wrong format'); |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | // Edge Case: Digits greater than or equal to input base |
| 45 | for (let digit of array) { |
| 46 | if (digit >= inputBase) { |
| 47 | throw new Error('Input has wrong format'); |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | // Convert from input base to decimal |
| 52 | let decimalValue = 0; |
| 53 | for (let i = 0; i < array.length; i++) { |
| 54 | decimalValue = decimalValue * inputBase + array[i]; |
| 55 | } |
| 56 | |
| 57 | // Edge Case: Zero input |
| 58 | if (decimalValue === 0) { |
| 59 | return [0]; |
| 60 | } |
| 61 | |
| 62 | // Convert from decimal to output base |
| 63 | const result = []; |
| 64 | while (decimalValue > 0) { |
| 65 | result.unshift(decimalValue % outputBase); |
| 66 | decimalValue = Math.floor(decimalValue / outputBase); |
| 67 | } |
| 68 | |
| 69 | return result; |
| 13 | 70 | }; |
| 71 | // Handled Edge Cases: invalid input base (less than 2), invalid output base (less than 2), empty input array, input with invalid digits (greater than or equal to base), input with leading zeros, input with negative digits, single digit input, zero input |