| 8 | 8 | * @param {number} takeDownCount |
| 9 | 9 | * @return {string[]} |
| 10 | 10 | */ |
| 11 | | export const recite = (initialBottlesCount, takeDownCount = 1) => { |
| 12 | | throw new Error('Remove this line and implement the function'); |
| 11 | export const recite = (initialBottlesCount, takeDownCount) => { |
| 12 | // If no parameters are provided, recite the entire song (99 bottles down to 0) |
| 13 | if (initialBottlesCount === undefined && takeDownCount === undefined) { |
| 14 | initialBottlesCount = 99; |
| 15 | takeDownCount = 100; // 99 down to 0 is 100 verses |
| 16 | } else { |
| 17 | // Handle edge cases for provided parameters |
| 18 | if (initialBottlesCount < 0) { |
| 19 | initialBottlesCount = 0; |
| 20 | } |
| 21 | |
| 22 | if (takeDownCount === undefined) { |
| 23 | takeDownCount = 1; |
| 24 | } else if (takeDownCount < 0) { |
| 25 | takeDownCount = 0; |
| 26 | } |
| 27 | |
| 28 | // Prevent infinite loop by limiting takeDownCount |
| 29 | if (takeDownCount > initialBottlesCount + 1) { |
| 30 | takeDownCount = initialBottlesCount + 1; |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | const result = []; |
| 35 | |
| 36 | for (let i = 0; i < takeDownCount; i++) { |
| 37 | const currentBottles = initialBottlesCount - i; |
| 38 | const nextBottles = currentBottles - 1; |
| 39 | |
| 40 | // Handle when current bottles is 0 |
| 41 | if (currentBottles === 0) { |
| 42 | result.push("No more bottles of beer on the wall, no more bottles of beer."); |
| 43 | result.push("Go to the store and buy some more, 99 bottles of beer on the wall."); |
| 44 | } |
| 45 | // Handle when current bottles is 1 |
| 46 | else if (currentBottles === 1) { |
| 47 | result.push("1 bottle of beer on the wall, 1 bottle of beer."); |
| 48 | result.push("Take it down and pass it around, no more bottles of beer on the wall."); |
| 49 | } |
| 50 | // Handle when current bottles is 2 |
| 51 | else if (currentBottles === 2) { |
| 52 | result.push("2 bottles of beer on the wall, 2 bottles of beer."); |
| 53 | result.push("Take one down and pass it around, 1 bottle of beer on the wall."); |
| 54 | } |
| 55 | // Handle normal cases (3 or more bottles) |
| 56 | else { |
| 57 | result.push(`${currentBottles} bottles of beer on the wall, ${currentBottles} bottles of beer.`); |
| 58 | result.push(`Take one down and pass it around, ${nextBottles} bottles of beer on the wall.`); |
| 59 | } |
| 60 | |
| 61 | // Add empty line between verses except for the last verse |
| 62 | if (i < takeDownCount - 1) { |
| 63 | result.push(""); |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | return result; |
| 13 | 68 | }; |