Skip to content

Instantly share code, notes, and snippets.

@AndrewGuard
Last active December 27, 2015 18:48
Show Gist options
  • Save AndrewGuard/7371992 to your computer and use it in GitHub Desktop.
Save AndrewGuard/7371992 to your computer and use it in GitHub Desktop.
Zoo-object_oriented_javascript
//------------------------------------------------------------------------------------------------------------------
// YOUR CODE: Create your Zoo "object literal" and Animal "constructor" and "prototypes" here.
//------------------------------------------------------------------------------------------------------------------
var Zoo = {}
Zoo.init = function(list_of_animals) {
this.animals = list_of_animals
}
Zoo.bipeds = function() {
var bipeds = [];
for(var i = 0; i < this.animals.length; i++) {
var thisAnimal = this.animals[i];
if(thisAnimal.isBiped()) {
bipeds.push(thisAnimal);
}
}
return bipeds;
}
// =======================================
var Zoo = {
init: function() {
this.animals = list_of_animals
},
bipeds: function() {
var bipeds = [];
for(var i = 0; i < this.animals.length; i++) {
var thisAnimal = this.animals[i];
if(thisAnimal.isBiped()) {
bipeds.push(thisAnimal);
}
}
return bipeds;
}
}
function Animal(species, legs) {
this.species = species;
this.legs = legs;
};
Animal.prototype.isBiped = function() {
return this.legs == 2;
}
// Animal.prototype.bipeds {
// legs === 2;
// }
// Animal.prototype.quadrupeds {
// legs === 4;
// }
//------------------------------------------------------------------------------------------------------------------
// DRIVER CODE: Do **NOT** change anything below this point. Your task is to implement code above to make this work.
//------------------------------------------------------------------------------------------------------------------
function assert(test, message) {
if (!test) {
throw "ERROR: " + message;
}
return true;
}
var animals = [
new Animal("Human", 2),
new Animal("Monkey", 2),
new Animal("Kangaroo", 2),
new Animal("Horse", 4),
new Animal("Cow", 4),
new Animal("Centipede", 100)
];
Zoo.init(animals);
assert(
Zoo.bipeds().length === 3, "the Zoo should have 3 bipeds"
);
assert(
Zoo.quadrupeds().length === 2, "the Zoo should have 2 bipeds"
);
assert(
animals[0].identify() === "I am a Human with 2 legs.", "humans have 2 legs"
);
assert(
animals[2].name === "Kangaroo", "expected 'Kangaroo'"
);
assert(
animals[0].identify === animals[5].identify, "only one implementation of the identify() function should exist"
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment