/javascript/beer-song/beer-song.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
var song = {
  // "n bottles of beer"
  // e.g. "10 bottles of beer" or "1 bottle of beer"
  bottles: function(n) {
    n = n || 'no more';
    return n + ' bottle' + (n == 1 ? '' : 's') + ' of beer';
  },

  // "n bottles of beer on the wall"
  // e.g. "10 bottles of beer on the wall" or "1 bottle of beer on the wall"
  bottles_on_wall: function(n) {
    return this.bottles(n) + ' on the wall';
  },

  // Sing verse number n (1-based)
  verse: function(n) {
    var lines = this.bottles_on_wall(n) + ', ' + this.bottles(n) + '.\n';

    if (n > 0) {
      lines += 'Take ' + (n == 1 ? 'it' : 'one') + ' down and pass it around, ' +
                this.bottles_on_wall(n-1) + '.\n';
    } else {
      // capitalize the first letter
      lines = lines[0].toUpperCase() + lines.slice(1);
      lines += 'Go to the store and buy some more, ' + this.bottles_on_wall(99) + '.\n';
    }
    return lines;
  },

  // Sing verses from m down to n, inclusive (1-based)
  sing: function(m, n) {
    var verses = [];
    var i;
    n = n || 0;
    for (i = m; i >= n; i--){
      verses.push(this.verse(i));
    }
    return verses.join('\n');
  }
};

module.exports = song;

Comments


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