/javascript/food-chain/food-chain.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
var song = {

  // Creatures swallowed, smallest first.
  creatures: [
    'fly',
    'spider',
    'bird',
    'cat',
    'dog',
    'goat',
    'cow',
    'horse'
  ],

  // Anything else to say about it?
  extras: {
    spider: "It wriggled and jiggled and tickled inside her.",
    bird: "How absurd to swallow a bird!",
    cat: "Imagine that, to swallow a cat!",
    dog: "What a hog, to swallow a dog!",
    goat: "Just opened her throat and swallowed a goat!",
    cow: "I don't know how she swallowed a cow!",
    horse: "She's dead, of course!"
  },

  // Get all the verses between first and last, inclusive
  // (1-based index)
  verses: function(first, last) {
    var song = '';
    for (var i=first; i <= last; i++) {
      song += this.verse(i) + '\n';
    }
    return song;
  },

  verse: function(n) {
    var creature = this.creatures[n-1];
    var extra = this.extras[creature];

    var lines = [];
    lines.push('I know an old lady who swallowed a ' + creature + '.');

    if (extra) {
      lines.push(extra);
    }

    if (creature != 'horse') {
      for (var i=n-1; i > 0; i--) {
        var predator = this.creatures[i];
        var prey = this.creatures[i-1];
        line = 'She swallowed the ' + predator + ' to catch the ' + prey;
        if (prey == 'spider') {
          line += ' that wriggled and jiggled and tickled inside her';
        }
        lines.push(line +'.');
      }

      lines.push("I don't know why she swallowed the fly. Perhaps she'll die.");
    }

    return lines.join("\n") + '\n';
  }
};

module.exports = song;

Comments


You're not logged in right now. Please login via GitHub to comment