Skip to content

Instantly share code, notes, and snippets.

@ynonp
Created October 24, 2012 14:56
Show Gist options
  • Save ynonp/3946550 to your computer and use it in GitHub Desktop.
Save ynonp/3946550 to your computer and use it in GitHub Desktop.
Todos Solution
// your code goes here
var Todos = function() {
var self = {};
var tasks = [];
var openedTasks = function() {
return tasks.filter( function(t) {return t.isOpen();});
};
self.addTask = function(task) {
tasks.push( task );
};
self.get = function(idx) {
var opened = openedTasks();
return opened[idx];
};
self.count = function() {
var opened = openedTasks();
return opened.length;
};
return self;
};
var Task = function(text) {
var self = {};
var open = true;
self.done = function() {
open = false;
};
self.isOpen = function() {
return open;
};
self.toString = function() {
return text;
};
return self;
};
var tasks = new Todos();
var t1 = new Task('Feed the dog');
var t2 = new Task('Clean up the house');
var t3 = new Task('Write JavaScript');
tasks.addTask(t1);
tasks.addTask(t2);
tasks.addTask(t3);
// print: I need to do 3 things
console.log('I need to do ' + tasks.count() + ' things');
t1.done();
t2.done();
// print: I need to do 1 thing
console.log('I need to do ' + tasks.count() + ' things');
// print: My task is: Write JavaScript
console.log('My task is: ' + tasks.get(0));
(function() {
// Insert Code Here
var MusicBox = function() {
var self = {};
var albums = [];
self.addAlbum = function( a ) {
albums.push( a );
};
self.favoriteAlbum = function() {
return albums.reduce(function(a, b) {
return a.countPlays() > b.countPlays() ? a : b;
});
};
return self;
};
var Album = function(artist, title) {
var self = {};
var count = 0;
self.play = function() {
console.log("Playing " + self);
count += 1;
};
self.toString = function() {
return artist + " - " + title;
};
self.countPlays = function() {
return count;
};
return self;
};
var box = new MusicBox(),
a1 = new Album("The Who", "Tommy"),
a2 = new Album("Tom Waits", "Closing Time"),
a3 = new 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