Pages

Thursday, September 29, 2016

Go, Dog. Go! (JavaScript)

// Classes

function Animal(name, percentAbility) {
  this.name = name;
  this.multiplier = percentAbility / 100;
}
Animal.prototype = {
  constructor: Animal,
  topSpeed: function() {
    return this.multiplier * this.typicalTopSpeed;
  },
  typeOfAnimal: undefined,
  typicalTopSpeed: undefined,
}

function Greyhound(name, percentAbility) {
  Animal.call(this, name, percentAbility);
}
Greyhound.prototype = Object.create(Animal.prototype);
Greyhound.prototype.constructor = Greyhound;
Greyhound.prototype.typeOfAnimal = "greyhound";
Greyhound.prototype.typicalTopSpeed = 43;

function Ostrich(name, percentAbility) {
  Animal.call(this, name, percentAbility);
}
Ostrich.prototype = Object.create(Animal.prototype);
Ostrich.prototype.constructor = Ostrich;
Ostrich.prototype.typeOfAnimal = "ostrich";
Ostrich.prototype.typicalTopSpeed = 40;

// Functions

function whoLoses(animal1, animal2) {
  if (animal1.topSpeed() > animal2.topSpeed()) {
    return animal2.name;
  }
  else if (animal2.topSpeed() > animal1.topSpeed()) {
    return animal1.name;
  }
  else {
    return "neither";
  }
}

function raceResults(animal1, animal2) {
  var results = "In a race between ";
  results += animal1.name + " the " + animal1.typeOfAnimal;
  results += " and ";
  results += animal2.name + " the " + animal2.typeOfAnimal;
  results += ", " + whoLoses(animal1, animal2);
  results += " loses.";
  return results;
}

// Objects

var grit = new Greyhound("Grit", 115);
var oliver = new Ostrich("Oliver", 120);

// Action

alert(raceResults(grit, oliver));