| 1 | | // |
| 2 | | // This is only a SKELETON file for the 'Beer Song' exercise. It's been provided as a |
| 3 | | // convenience to get you started writing code faster. |
| 4 | | // |
| 5 | | |
| 6 | | /** |
| 7 | | * @param {number} initialBottlesCount |
| 8 | | * @param {number} takeDownCount |
| 9 | | * @return {string[]} |
| 1 | /* |
| 2 | * Recites the lyrics to the '99 Bottles of Beer' song. |
| 3 | * @param {number} initialBottlesCount - The starting number of bottles (0-99). |
| 4 | * @param {number} takeDownCount - The number of verses to recite (default: 1). |
| 5 | * @return {string[]} - An array of strings representing the lyrics. |
| 10 | 6 | */ |
| 11 | 7 | export const recite = (initialBottlesCount, takeDownCount = 1) => { |
| 12 | | throw new Error('Remove this line and implement the function'); |
| 8 | // Edge Case: Handle invalid inputs by returning an empty array |
| 9 | if (typeof initialBottlesCount !== 'number' || typeof takeDownCount !== 'number' || |
| 10 | initialBottlesCount < 0 || initialBottlesCount > 99 || takeDownCount < 0) { |
| 11 | return []; |
| 12 | } |
| 13 | |
| 14 | // Edge Case: If takeDownCount is 0, return an empty array |
| 15 | if (takeDownCount === 0) { |
| 16 | return []; |
| 17 | } |
| 18 | |
| 19 | const verses = []; |
| 20 | |
| 21 | let currentBottles = initialBottlesCount; |
| 22 | for (let i = 0; i < takeDownCount; i++) { |
| 23 | // Handle wrap-around: if we go below 0, we should continue with 99 bottles |
| 24 | if (currentBottles < 0) { |
| 25 | // After 0 bottles, we continue with 99 bottles |
| 26 | currentBottles = 99; |
| 27 | } |
| 28 | |
| 29 | // Handle special cases for 0, 1, and 2 bottles |
| 30 | if (currentBottles === 0) { |
| 31 | verses.push('No more bottles of beer on the wall, no more bottles of beer.'); |
| 32 | verses.push('Go to the store and buy some more, 99 bottles of beer on the wall.'); |
| 33 | } else if (currentBottles === 1) { |
| 34 | verses.push('1 bottle of beer on the wall, 1 bottle of beer.'); |
| 35 | verses.push('Take it down and pass it around, no more bottles of beer on the wall.'); |
| 36 | } else if (currentBottles === 2) { |
| 37 | verses.push('2 bottles of beer on the wall, 2 bottles of beer.'); |
| 38 | verses.push('Take one down and pass it around, 1 bottle of beer on the wall.'); |
| 39 | } else { |
| 40 | verses.push(`${currentBottles} bottles of beer on the wall, ${currentBottles} bottles of beer.`); |
| 41 | verses.push(`Take one down and pass it around, ${currentBottles - 1} bottles of beer on the wall.`); |
| 42 | } |
| 43 | |
| 44 | // Add an empty string after each verse except the last one |
| 45 | if (i < takeDownCount - 1) { |
| 46 | verses.push(''); |
| 47 | } |
| 48 | |
| 49 | // Decrement the bottle count for the next iteration |
| 50 | currentBottles--; |
| 51 | } |
| 52 | |
| 53 | return verses; |
| 13 | 54 | }; |
| 55 | |
| 56 | // Handled Edge Cases: Invalid inputs (non-numbers, out of range), takeDownCount=0, currentBottles<0 |