Skip to content

Instantly share code, notes, and snippets.

@LilyMGoh
Forked from dbc-challenges/zoo.js
Last active December 23, 2015 09:38
Show Gist options
  • Save LilyMGoh/6615488 to your computer and use it in GitHub Desktop.
Save LilyMGoh/6615488 to your computer and use it in GitHub Desktop.
//------------------------------------------------------------------------------------------------------------------
// YOUR CODE: Create your Zoo "object literal" and Animal "constructor" and "prototypes" here.
//------------------------------------------------------------------------------------------------------------------
function Animal(name, legNum){
this.name = name;
this.legNum = legNum;
}
// if something is a function then you can define prototype for it
// var a1 = new Animal("Human", 2);
Animal.prototype = {
identify: function() { return "I am a " + this.name + " with " + this.legNum +" legs." }
}
// ... is the same as ...
// Animal.prototype.foo = "bar";
// Animal.prototype.identify = function() { return "I am a " + this.name + " with " + this.legNum +" legs." };
// var a2 = new Animal("Bear", 4);
// var a = new Animal("Human", 2);
// a.identify = function() {}
// var b = new Animal("Bird", 2);
// b.identify() // error!
// Animal is a function (used as a constructor-style object)
// when we want to assign properties to the obj, then we need 'this'
var Zoo = {
zooAnimals: [],
init: function(animals){
for(i=0; i< animals.length; i++){
this.zooAnimals.push(animals[i])
}
},
categorize: function(legNum){
category = []
for(i=0; i< this.zooAnimals.length; i++){
if (this.zooAnimals[i].legNum === legNum) {
category.push(this.zooAnimals[i])
}
}
return category
},
bipeds: function(){ return this.categorize(2) },
quadrupeds: function(){ return this.categorize(4) }
}
// Zoo is an obj literal, not a contructor
//------------------------------------------------------------------------------------------------------------------
// 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 quadrupeds"
);
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