| 9 | 9 | * @return {string[]} |
| 10 | 10 | */ |
| 11 | 11 | export const recite = (initialBottlesCount, takeDownCount = 1) => { |
| 12 | | throw new Error('Remove this line and implement the function'); |
| 12 | // Edge Case: Invalid input types |
| 13 | if (typeof initialBottlesCount !== 'number' || typeof takeDownCount !== 'number') { |
| 14 | throw new Error('Inputs must be numbers'); |
| 15 | } |
| 16 | |
| 17 | // Edge Case: Negative takeDownCount |
| 18 | if (takeDownCount < 0) { |
| 19 | throw new Error('takeDownCount must be non-negative'); |
| 20 | } |
| 21 | |
| 22 | // Edge Case: Initial count greater than 99 |
| 23 | if (initialBottlesCount > 99) { |
| 24 | throw new Error('initialBottlesCount must not exceed 99'); |
| 25 | } |
| 26 | |
| 27 | const result = []; |
| 28 | let currentBottles = initialBottlesCount; |
| 29 | |
| 30 | for (let i = 0; i < takeDownCount; i++) { |
| 31 | // Edge Case: When we reach negative bottles, stop reciting |
| 32 | if (currentBottles < 0) { |
| 33 | break; |
| 34 | } |
| 35 | |
| 36 | // Handle the special case for 0 bottles |
| 37 | if (currentBottles === 0) { |
| 38 | result.push('No more bottles of beer on the wall, no more bottles of beer.'); |
| 39 | result.push('Go to the store and buy some more, 99 bottles of beer on the wall.'); |
| 40 | // Edge Case: After reaching 0, we don't continue to negative numbers in a single recitation |
| 41 | break; |
| 42 | } |
| 43 | |
| 44 | // Determine bottle text (singular vs plural) |
| 45 | const currentBottleText = currentBottles === 1 ? 'bottle' : 'bottles'; |
| 46 | const nextBottleText = (currentBottles - 1) === 1 ? 'bottle' : 'bottles'; |
| 47 | |
| 48 | // Determine next bottle count text |
| 49 | const nextBottleCount = currentBottles - 1 > 0 ? |
| 50 | `${currentBottles - 1}` : |
| 51 | (currentBottles - 1 === 0 ? 'no more' : '99'); |
| 52 | |
| 53 | // Handle special case for 1 bottle (different verb) |
| 54 | const action = currentBottles === 1 ? 'Take it down and pass it around' : 'Take one down and pass it around'; |
| 55 | |
| 56 | // Add the two lines of the verse |
| 57 | result.push(`${currentBottles} ${currentBottleText} of beer on the wall, ${currentBottles} ${currentBottleText} of beer.`); |
| 58 | result.push(`${action}, ${nextBottleCount} ${nextBottleText} of beer on the wall.`); |
| 59 | |
| 60 | // Move to the next verse |
| 61 | currentBottles--; |
| 62 | |
| 63 | // Add empty line between verses, except for the last one |
| 64 | if (i < takeDownCount - 1 && currentBottles >= 0) { |
| 65 | result.push(''); |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | return result; |
| 13 | 70 | }; |
| 71 | |
| 72 | // Handled Edge Cases: Invalid input types, negative takeDownCount, initial count greater than 99, reaching negative bottles, special case for 0 bottles, singular vs plural bottle text, different verb for 1 bottle, empty line between verses |