| 4 | 4 | // |
| 5 | 5 | |
| 6 | 6 | export class Palindromes { |
| 7 | | static generate() { |
| 8 | | throw new Error('Remove this line and implement the function'); |
| 7 | static generate({ minFactor, maxFactor }) { |
| 8 | // Edge Case: Invalid range where minFactor > maxFactor |
| 9 | if (minFactor > maxFactor) { |
| 10 | throw new Error('min must be <= max'); |
| 11 | } |
| 12 | |
| 13 | let palindromes = {}; |
| 14 | let smallest = null; |
| 15 | let largest = null; |
| 16 | |
| 17 | // Iterate through all possible factor pairs |
| 18 | for (let i = minFactor; i <= maxFactor; i++) { |
| 19 | for (let j = i; j <= maxFactor; j++) { |
| 20 | const product = i * j; |
| 21 | |
| 22 | // Check if the product is a palindrome |
| 23 | if (this.isPalindrome(product)) { |
| 24 | // Initialize the palindrome entry if it doesn't exist |
| 25 | if (!palindromes[product]) { |
| 26 | palindromes[product] = []; |
| 27 | } |
| 28 | |
| 29 | // Add the factor pair |
| 30 | palindromes[product].push([i, j]); |
| 31 | |
| 32 | // Update smallest and largest |
| 33 | if (smallest === null || product < smallest) { |
| 34 | smallest = product; |
| 35 | } |
| 36 | if (largest === null || product > largest) { |
| 37 | largest = product; |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | // Edge Case: No palindromes found in the range |
| 44 | if (smallest === null && largest === null) { |
| 45 | return { |
| 46 | largest: { value: null, factors: [] }, |
| 47 | smallest: { value: null, factors: [] } |
| 48 | }; |
| 49 | } |
| 50 | |
| 51 | // Edge Case: Only one palindrome found (smallest and largest are the same) |
| 52 | if (smallest === largest) { |
| 53 | return { |
| 54 | largest: { value: largest, factors: palindromes[largest] }, |
| 55 | smallest: { value: smallest, factors: palindromes[smallest] } |
| 56 | }; |
| 57 | } |
| 58 | |
| 59 | return { |
| 60 | largest: { value: largest, factors: palindromes[largest] }, |
| 61 | smallest: { value: smallest, factors: palindromes[smallest] } |
| 62 | }; |
| 63 | } |
| 64 | |
| 65 | static isPalindrome(number) { |
| 66 | const str = String(number); |
| 67 | return str === str.split('').reverse().join(''); |
| 9 | 68 | } |
| 10 | 69 | } |
| 70 | |
| 71 | // Handled Edge Cases: Invalid range where minFactor > maxFactor, No palindromes found in the range, Only one palindrome found (smallest and largest are the same) |