Created
October 9, 2015 11:25
-
-
Save itinsley/1e9bbf8746f3b80a6768 to your computer and use it in GitHub Desktop.
Collections?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Animal = function(classification, legs_count, size) { | |
this.classification = classification; | |
this.legs_count = legs_count; | |
this.size = size; | |
} | |
// An instance method; | |
Animal.prototype.description = function(){ | |
return this.size + " " + this.classification + "with " + this.legs_count + " legs"; | |
} | |
// Namespaced functions | |
Animal.isDog = function(animal){ | |
return animal.classification==='dog'; | |
}; | |
Animal.hasOneLeg = function(animal){ | |
return animal.legs_count===1; | |
}; | |
//Static Methods | |
Animal.dogsOnly = function(){ | |
return Animal.all().filter(Animal.isDog); | |
} | |
Animal.oneLeg = function(){ | |
return Animal.all().filter(Animal.hasOneLeg); | |
} | |
Animal.all = function(){ | |
return [ | |
new Animal("dog", 4, 'small'), | |
new Animal("dog", 1, 'small'), | |
new Animal("cat", 4, 'tiny'), | |
new Animal("bird", 2, 'iddybiddy'), | |
new Animal("cow", 1, 'huge') | |
] | |
} | |
// console.log("All the animals"); | |
// console.log(Animal.all()); | |
// console.log("All the dogs"); | |
// console.log(Animal.dogsOnly()); | |
// console.log("Dogs descriptions"); | |
// dogs = Animal.dogsOnly(); | |
// dogs.forEach(function(dog){ | |
// console.log(dog.description()); | |
// }) | |
// console.log("One legged animals"); | |
// console.log(Animal.oneLeg()); | |
console.log("has one leg") | |
console.log(Animal.all().filter(Animal.hasOneLeg)); | |
console.log("is a dog") | |
console.log(Animal.all().filter(Animal.isDog)); | |
console.log("one legged dog, chaining filters") | |
console.log(Animal.all().filter(Animal.isDog).filter(Animal.hasOneLeg)); | |
//Collections and chaining | |
console.log("Dogs with one leg"); | |
console.log(Animal.dogsOnly().filter(Animal.hasOneLeg)); | |
//OR | |
console.log("Dogs with one leg"); | |
console.log(Animal.all().filter(Animal.isDog));//.filter(Animal.hasOneLeg)); | |
//Static | |
console.log("static") | |
console.log(Animal.oneLeg()); | |
console.log(Animal.dogsOnly()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment