| 3 | 3 | // convenience to get you started writing code faster. |
| 4 | 4 | // |
| 5 | 5 | |
| 6 | | export const largestProduct = () => { |
| 7 | | throw new Error('Remove this line and implement the function'); |
| 6 | export const largestProduct = (digits, span) => { |
| 7 | // Edge Case: span is negative |
| 8 | if (span < 0) { |
| 9 | throw new Error('span must not be negative'); |
| 10 | } |
| 11 | |
| 12 | // Edge Case: span is zero |
| 13 | if (span === 0) { |
| 14 | return 1; |
| 15 | } |
| 16 | |
| 17 | // Edge Case: empty input string |
| 18 | if (digits === '') { |
| 19 | throw new Error('span must not exceed string length'); |
| 20 | } |
| 21 | |
| 22 | // Edge Case: span greater than input length |
| 23 | if (span > digits.length) { |
| 24 | throw new Error('span must not exceed string length'); |
| 25 | } |
| 26 | |
| 27 | // Edge Case: input containing non-digit characters |
| 28 | if (!/^\d+$/.test(digits)) { |
| 29 | throw new Error('digits input must only contain digits'); |
| 30 | } |
| 31 | |
| 32 | let maxProduct = 0; |
| 33 | |
| 34 | for (let i = 0; i <= digits.length - span; i++) { |
| 35 | let product = 1; |
| 36 | for (let j = 0; j < span; j++) { |
| 37 | product *= parseInt(digits[i + j], 10); |
| 38 | } |
| 39 | if (product > maxProduct) { |
| 40 | maxProduct = product; |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | return maxProduct; |
| 8 | 45 | }; |
| 46 | |
| 47 | // Handled Edge Cases: span is negative, span is zero, empty input string, span greater than input length, input containing non-digit characters |