| 9 | 9 | * @returns {{smallest: {value: number|null, factors: number[][]}, largest: {value: number|null, factors: number[][]}}} |
| 10 | 10 | */ |
| 11 | 11 | static generate(options) { |
| 12 | | throw new Error('Remove this line and implement the function'); |
| 12 | const { minFactor, maxFactor } = options; |
| 13 | |
| 14 | // Edge Case: invalid range where min > max |
| 15 | if (minFactor > maxFactor) { |
| 16 | throw new Error('min must be <= max'); |
| 17 | } |
| 18 | |
| 19 | let smallestPalindrome = null; |
| 20 | let largestPalindrome = null; |
| 21 | let smallestFactors = []; |
| 22 | let largestFactors = []; |
| 23 | |
| 24 | |
| 25 | // Helper function to check if a number is palindrome |
| 26 | const isPalindrome = (num) => { |
| 27 | const str = num.toString(); |
| 28 | return str === str.split('').reverse().join(''); |
| 29 | }; |
| 30 | |
| 31 | // Iterate through all possible products |
| 32 | for (let i = minFactor; i <= maxFactor; i++) { |
| 33 | for (let j = i; j <= maxFactor; j++) { // j starts from i to avoid duplicate pairs |
| 34 | const product = i * j; |
| 35 | |
| 36 | if (isPalindrome(product)) { |
| 37 | // Handle smallest palindrome |
| 38 | if (smallestPalindrome === null || product < smallestPalindrome) { |
| 39 | smallestPalindrome = product; |
| 40 | smallestFactors = [[i, j]]; |
| 41 | } else if (product === smallestPalindrome) { |
| 42 | smallestFactors.push([i, j]); |
| 43 | } |
| 44 | |
| 45 | // Handle largest palindrome |
| 46 | if (largestPalindrome === null || product > largestPalindrome) { |
| 47 | largestPalindrome = product; |
| 48 | largestFactors = [[i, j]]; |
| 49 | } else if (product === largestPalindrome) { |
| 50 | largestFactors.push([i, j]); |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | // Edge Case: no palindrome products in range |
| 57 | if (smallestPalindrome === null && largestPalindrome === null) { |
| 58 | return { |
| 59 | smallest: { value: null, factors: [] }, |
| 60 | largest: { value: null, factors: [] } |
| 61 | }; |
| 62 | } |
| 63 | |
| 64 | return { |
| 65 | smallest: { value: smallestPalindrome, factors: smallestFactors }, |
| 66 | largest: { value: largestPalindrome, factors: largestFactors } |
| 67 | }; |
| 13 | 68 | } |
| 14 | 69 | } |
| 70 | |
| 71 | // Handled Edge Cases: invalid range where min > max, empty range or single number range, no palindrome products in range |