| 9 | 9 | * @return {string} |
| 10 | 10 | */ |
| 11 | 11 | verse(number) { |
| 12 | | throw new Error('Remove this line and implement the function'); |
| 12 | // Edge Case: Invalid verse number (less than 1 or greater than 8) |
| 13 | if (number < 1 || number > 8) { |
| 14 | throw new Error('Verse number must be between 1 and 8'); |
| 15 | } |
| 16 | |
| 17 | const animals = [ |
| 18 | 'fly', |
| 19 | 'spider', |
| 20 | 'bird', |
| 21 | 'cat', |
| 22 | 'dog', |
| 23 | 'goat', |
| 24 | 'cow', |
| 25 | 'horse' |
| 26 | ]; |
| 27 | |
| 28 | const reactions = [ |
| 29 | null, |
| 30 | 'It wriggled and jiggled and tickled inside her.', |
| 31 | 'How absurd to swallow a bird!', |
| 32 | 'Imagine that, to swallow a cat!', |
| 33 | 'What a hog, to swallow a dog!', |
| 34 | 'Just opened her throat and swallowed a goat!', |
| 35 | "I don't know how she swallowed a cow!", |
| 36 | "She's dead, of course!" |
| 37 | ]; |
| 38 | |
| 39 | // Edge Case: First verse (fly only) |
| 40 | if (number === 1) { |
| 41 | return `I know an old lady who swallowed a fly.\nI don't know why she swallowed the fly. Perhaps she'll die.\n`; |
| 42 | } |
| 43 | |
| 44 | // Edge Case: Last verse (horse - special ending) |
| 45 | if (number === 8) { |
| 46 | return `I know an old lady who swallowed a horse.\nShe's dead, of course!\n`; |
| 47 | } |
| 48 | |
| 49 | let result = `I know an old lady who swallowed a ${animals[number - 1]}.\n${reactions[number - 1]}\n`; |
| 50 | |
| 51 | // Build the cumulative part |
| 52 | for (let i = number - 1; i > 0; i--) { |
| 53 | if (i === 2) { |
| 54 | // Special case for spider with description |
| 55 | result += `She swallowed the ${animals[i]} to catch the ${animals[i - 1]} that wriggled and jiggled and tickled inside her.\n`; |
| 56 | } else { |
| 57 | result += `She swallowed the ${animals[i]} to catch the ${animals[i - 1]}.\n`; |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | result += `I don't know why she swallowed the fly. Perhaps she'll die.\n`; |
| 62 | return result; |
| 13 | 63 | } |
| 14 | 64 | |
| 15 | 65 | /** |
| 18 | 68 | * @return {string} |
| 19 | 69 | */ |
| 20 | 70 | verses(first, last) { |
| 21 | | throw new Error('Remove this line and implement the function'); |
| 71 | // Edge Case: Invalid range (first greater than last) |
| 72 | if (first > last) { |
| 73 | throw new Error('First verse cannot be greater than last verse'); |
| 74 | } |
| 75 | |
| 76 | // Edge Case: Invalid verse numbers (out of range) |
| 77 | if (first < 1 || last > 8) { |
| 78 | throw new Error('Verse numbers must be between 1 and 8'); |
| 79 | } |
| 80 | |
| 81 | let result = ''; |
| 82 | for (let i = first; i <= last; i++) { |
| 83 | result += this.verse(i); |
| 84 | if (i < last) { |
| 85 | result += '\n'; |
| 86 | } |
| 87 | } |
| 88 | return result; |
| 22 | 89 | } |
| 23 | 90 | } |
| 91 | |
| 92 | // Handled Edge Cases: Invalid verse number, first verse (fly only), last verse (horse), invalid range, out of range verse numbers |