| 4 | 4 | // |
| 5 | 5 | |
| 6 | 6 | export const say = (n) => { |
| 7 | | throw new Error('Remove this line and implement the function'); |
| 7 | // Edge Case: Numbers outside the supported range |
| 8 | if (n < 0 || n > 999999999999) { |
| 9 | throw new Error('Number must be between 0 and 999,999,999,999.'); |
| 10 | } |
| 11 | |
| 12 | // Edge Case: Zero value |
| 13 | if (n === 0) { |
| 14 | return 'zero'; |
| 15 | } |
| 16 | |
| 17 | const smallNumbers = [ |
| 18 | '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', |
| 19 | 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', |
| 20 | 'seventeen', 'eighteen', 'nineteen' |
| 21 | ]; |
| 22 | |
| 23 | const tens = [ |
| 24 | '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' |
| 25 | ]; |
| 26 | |
| 27 | const scales = [ |
| 28 | '', 'thousand', 'million', 'billion' |
| 29 | ]; |
| 30 | |
| 31 | // Helper function to convert a number less than 1000 to words |
| 32 | const convertLessThanThousand = (num) => { |
| 33 | let result = ''; |
| 34 | |
| 35 | // Handle hundreds place |
| 36 | if (num >= 100) { |
| 37 | result += smallNumbers[Math.floor(num / 100)] + ' hundred'; |
| 38 | num %= 100; |
| 39 | if (num > 0) { |
| 40 | result += ' '; |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | // Handle tens and ones place |
| 45 | if (num >= 20) { |
| 46 | result += tens[Math.floor(num / 10)]; |
| 47 | if (num % 10 > 0) { |
| 48 | result += '-' + smallNumbers[num % 10]; |
| 49 | } |
| 50 | } else if (num > 0) { |
| 51 | result += smallNumbers[num]; |
| 52 | } |
| 53 | |
| 54 | return result; |
| 55 | }; |
| 56 | |
| 57 | let result = ''; |
| 58 | let scaleIndex = 0; |
| 59 | |
| 60 | // Edge Case: Numbers requiring hyphenation (handled in convertLessThanThousand) |
| 61 | // Edge Case: Numbers with trailing zeros (handled by checking if part > 0) |
| 62 | // Edge Case: Boundary values like 100, 1000, 1000000 (handled by the algorithm) |
| 63 | |
| 64 | while (n > 0) { |
| 65 | const part = n % 1000; |
| 66 | if (part > 0) { |
| 67 | let partStr = convertLessThanThousand(part); |
| 68 | if (scaleIndex > 0) { |
| 69 | partStr += ' ' + scales[scaleIndex]; |
| 70 | } |
| 71 | if (result) { |
| 72 | result = partStr + ' ' + result; |
| 73 | } else { |
| 74 | result = partStr; |
| 75 | } |
| 76 | } |
| 77 | n = Math.floor(n / 1000); |
| 78 | scaleIndex++; |
| 79 | } |
| 80 | |
| 81 | return result; |
| 8 | 82 | }; |
| 83 | |
| 84 | // Handled Edge Cases: Negative numbers, Numbers exceeding maximum supported value, Zero value, Numbers requiring hyphenation, Numbers with trailing zeros, Boundary values like 100, 1000, 1000000 |