Skip to content

Instantly share code, notes, and snippets.

@ynonp
Created February 11, 2012 17:26
Show Gist options
  • Save ynonp/1802762 to your computer and use it in GitHub Desktop.
Save ynonp/1802762 to your computer and use it in GitHub Desktop.
music box solution
(function() {
var MusicBox = function() {
var _albums = [];
var self = {
addAlbum: function(album) {
_albums.push(album);
},
favoriteAlbum: function() {
if ( _albums.length === 0 ) {
return null;
}
var fav = _albums[0];
for ( var i=1; i < _albums.length; ++i ) {
if ( _albums[i].getPlayCounter() > fav.getPlayCounter() ) {
fav = _albums[i];
}
}
return fav.toString();
}
};
return self;
};
var Album = function(artist, title) {
var _play_counter = 0;
var self = {
toString: function() { return artist + " - " + title; },
play: function() {
console.log(self.toString());
_play_counter += 1;
},
getPlayCounter: function() { return _play_counter; }
};
return self;
};
var box = MusicBox(),
a1 = Album("The Who", "Tommy"),
a2 = Album("Tom Waits", "Closing Time"),
a3 = Album("John Cale", "Paris 1919"),
favorite;
box.addAlbum(a1);
box.addAlbum(a2);
box.addAlbum(a3);
a1.play(); // prints "Playing The Who - Tommy"
a2.play(); // prints "Playing John Cale - Paris 1919"
a1.play(); // prints "Playing The Who - Tommy"
favorite = box.favoriteAlbum();
// prints "favorite album is The Who - Tommy"
console.log("favorite album is " + favorite);
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment