Javascript Challenge
by Luiza CICONE
HTML
<pre></pre>
JavaScript
// todo: add your code here :-)
function Price(bottles) {
this.bottles = bottles;
}
Price.prototype.toEuro = function() {
var sum = 0;
this.bottles.forEach(function(item) {
sum += item.price;
});
return sum;
}
Price.prototype.toDollar = function() {
return this.toEuro() * 0.8;
}
function Bottle(name, price) {
this.name = name;
this.price = price;
}
function Cellar() {
this.bottles = [];
this.price = new Price(this.bottles);
}
Cellar.prototype.addBottle = function(name, price) {
var bottle = new Bottle(name, price);
this.bottles.push(bottle);
}
Cellar.prototype.getBottle = function(name) {
for (var i in this.bottles) {
var bottle = this.bottles[i];
if (bottle.name === name) {
return bottle;
}
}
}
Cellar.prototype.getPrice = function() {
return this.price;
}
// expected output:
// ## Verifying results ## (index):87
// price1 20 true (index):90
// price2 16 true (index):91
// price3 16 true (index):97
// price4 12.8 true
// test case
var cellar = new Cellar();
cellar.addBottle("jurancon", 7);
var bottle = cellar.getBottle("jurancon");
cellar.addBottle("layon", 12);
bottle.price = 8;
var price = cellar.getPrice();
log("");
log("## Verifying results ##");
// check results (1)
log(" price1 " + price.toEuro() + " " + (price.toEuro() === 20));
log(" price2 " + price.toDollar() + " " + (price.toDollar() === 16));
// change price of the bottle
bottle.price = 4;
// check results (2)
log(" price3 " + price.toEuro() + " " + (price.toEuro() === 16));
log(" price4 " + price.toDollar() + " " + (price.toDollar() === 12.8));
function log(s) {
var c = $('pre');
c.text(c.text() + s + '\n');
}
function err(s) {
log('failed: ' + s);
}