| 8 | 8 | * @returns {string} |
| 9 | 9 | */ |
| 10 | 10 | export const say = (n) => { |
| 11 | | throw new Error('Remove this line and implement the function'); |
| 11 | // Edge Case: Check if input is a number |
| 12 | if (typeof n !== 'number' || !isFinite(n)) { |
| 13 | throw new Error('Number must be between 0 and 999,999,999,999.'); |
| 14 | } |
| 15 | |
| 16 | // Edge Case: Check if number is an integer |
| 17 | if (!Number.isInteger(n)) { |
| 18 | throw new Error('Number must be between 0 and 999,999,999,999.'); |
| 19 | } |
| 20 | |
| 21 | // Edge Case: Check if number is within valid range |
| 22 | if (n < 0 || n > 999999999999) { |
| 23 | throw new Error('Number must be between 0 and 999,999,999,999.'); |
| 24 | } |
| 25 | |
| 26 | // Edge Case: Handle zero separately |
| 27 | if (n === 0) { |
| 28 | return 'zero'; |
| 29 | } |
| 30 | |
| 31 | const ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', |
| 32 | 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', |
| 33 | 'seventeen', 'eighteen', 'nineteen']; |
| 34 | |
| 35 | const tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']; |
| 36 | |
| 37 | const scales = ['', 'thousand', 'million', 'billion']; |
| 38 | |
| 39 | // Helper function to convert a number less than 1000 to words |
| 40 | function convertLessThanThousand(num) { |
| 41 | let result = ''; |
| 42 | |
| 43 | // Handle hundreds place |
| 44 | if (num >= 100) { |
| 45 | result += ones[Math.floor(num / 100)] + ' hundred'; |
| 46 | num %= 100; |
| 47 | if (num > 0) { |
| 48 | result += ' '; |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | // Handle tens and ones place |
| 53 | if (num >= 20) { |
| 54 | result += tens[Math.floor(num / 10)]; |
| 55 | num %= 10; |
| 56 | if (num > 0) { |
| 57 | result += '-' + ones[num]; |
| 58 | } |
| 59 | } else if (num > 0) { |
| 60 | result += ones[num]; |
| 61 | } |
| 62 | |
| 63 | return result; |
| 64 | } |
| 65 | |
| 66 | // Edge Case: Handle numbers less than 1000 |
| 67 | if (n < 1000) { |
| 68 | return convertLessThanThousand(n); |
| 69 | } |
| 70 | |
| 71 | let result = ''; |
| 72 | let scaleIndex = 0; |
| 73 | |
| 74 | while (n > 0) { |
| 75 | const chunk = n % 1000; |
| 76 | if (chunk !== 0) { |
| 77 | const chunkWords = convertLessThanThousand(chunk); |
| 78 | if (scaleIndex > 0) { |
| 79 | result = chunkWords + ' ' + scales[scaleIndex] + (result ? ' ' + result : ''); |
| 80 | } else { |
| 81 | result = chunkWords + (result ? ' ' + result : ''); |
| 82 | } |
| 83 | } |
| 84 | n = Math.floor(n / 1000); |
| 85 | scaleIndex++; |
| 86 | } |
| 87 | |
| 88 | return result; |
| 12 | 89 | }; |
| 90 | |
| 91 | // Handled Edge Cases: negative numbers, numbers outside the valid range (0-999,999,999,999), zero value, invalid input types (non-numeric) |