Data Abstraction Hacks
An intro to data abstraction
Popcorn Hack #1
Create a child class of the class Appliance, and call it’s name() function
%%js
class Appliance {
constructor(name) {
this.name = name;
}
getName() {
return "I am a " + this.constructor.name + " and my model is " + this.name;
}
}
// Below this name the class and cause it to inherit from the Appliance class
class Microwave extends Appliance {
constructor(name) {
super(name);
}
}
var myMicrowave = new Microwave("Panasonic");
console.log(myMicrowave.getName());
<IPython.core.display.Javascript object>
Popcorn Hack #2
Create child classes of the product class with items, and add parameters depending on what it is. An example is provided of a bagel.
%%js
class Product {
constructor(price, size, taxRate, weight) {
this.price = price;
this.size = size;
this.taxRate = taxRate;
this.weight = weight;
}
getPrice() {
return this.price + this.taxRate * this.price;
}
product() {
const className = this.constructor.name.toLowerCase();
return "You are ordering a " + className + " with a price of " + this.getPrice() + " dollars, a size of " + this.size + " and a weight of " + this.weight + " grams.";
}
}
class Bagel extends Product {
constructor(price, size, taxRate, weight, flavor, isToasted) {
super(price, size, taxRate, weight);
this.flavor = flavor;
this.isToasted = isToasted;
}
getPrice() {
return super.getPrice() * this.size;
}
product() {
return super.product() + " It has a flavor of " + this.flavor + " and it is " + (this.isToasted ? "toasted" : "not toasted") + ".";
}
}
var sesameBagel = new Bagel(1.5, 2, 0.07, 100, "sesame", true);
console.log(sesameBagel.product());
class Apple extends Product {
constructor(price, size, taxRate, weight, variety, isOrganic) {
super(price, size, taxRate, weight);
this.variety = variety;
this.isOrganic = isOrganic;
}
product() {
return super.product() + " It is a " + this.variety + " variety and it is " + (this.isOrganic ? "organic" : "not organic") + ".";
}
}
var galaApple = new Apple(0.5, 1, 0.07, 150, "Gala", true);
console.log(galaApple.product());
class Coffee extends Product {
constructor(price, size, taxRate, weight, roast, isDecaf) {
super(price, size, taxRate, weight);
this.roast = roast;
this.isDecaf = isDecaf;
}
product() {
return super.product() + " It is a " + this.roast + " roast and it is " + (this.isDecaf ? "decaffeinated" : "not decaffeinated") + ".";
}
}
var darkRoastCoffee = new Coffee(3.0, 1, 0.07, 250, "dark", false);
console.log(darkRoastCoffee.product());
<IPython.core.display.Javascript object>