function Hamburger(size, stuffing) {
this.validateSize(size);
this.validateStuffing(stuffing);
this.size = size;
this.stuffing = stuffing;
this.toppings = [];
this.pricesAndCalorics = {};
this.pricesAndCalorics[Hamburger.SIZE_BIG] = {price: 100, calories: 40};
this.pricesAndCalorics[Hamburger.SIZE_SMALL] = {price: 50, calories: 20};
this.pricesAndCalorics[Hamburger.STUFFING_CHEESE] = {price: 10, calories: 20};
this.pricesAndCalorics[Hamburger.STUFFING_SALAD] = {price: 20, calories: 5};
this.pricesAndCalorics[Hamburger.STUFFING_POTATOES] = {price: 15, calories: 10};
this.pricesAndCalorics[Hamburger.TOPPING_SAUCE] = {price: 15, calories: 0};
this.pricesAndCalorics[Hamburger.TOPPING_MAYO] = {price: 20, calories: 5};
}
Hamburger.SIZE_BIG = "BIG";
Hamburger.SIZE_SMALL = "SMALL";
Hamburger.STUFFING_CHEESE = "CHEESE";
Hamburger.STUFFING_SALAD = "SALAD";
Hamburger.STUFFING_POTATOES = "POTATOES";
Hamburger.TOPPING_SAUCE = "SAUCE";
Hamburger.TOPPING_MAYO = "MAYO";
Hamburger.prototype.validateSize = function (size) {
if (size != Hamburger.SIZE_BIG &&
size != Hamburger.SIZE_SMALL) {
throw new Error( size + " - неправильный размер" );
}
}
Hamburger.prototype.validateStuffing = function (stuffing) {
if (stuffing != Hamburger.STUFFING_CHEESE &&
stuffing != Hamburger.STUFFING_SALAD &&
stuffing != Hamburger.STUFFING_POTATOES) {
throw new Error( stuffing + " - неправильная начинка" );
}
}
Hamburger.prototype.addTopping = function (topping) {
if (topping != Hamburger.TOPPING_SAUCE &&
topping != Hamburger.TOPPING_MAYO) {
throw new Error( topping + " - неизвестная добавка");
};
if (this.toppings.indexOf(topping) >= 0) {
throw new Error("Одну и ту же добавку нельзя использовать больше одного раза!");
};
this.toppings.push(topping);
}
Hamburger.prototype.calculateCalories = function () {
var calories = 0;
var arr = this.pricesAndCalorics;
calories += arr[this.size].calories;
calories += arr[this.stuffing].calories;
for (var i = 0; i < this.toppings.length; i++) {
calories += arr[this.toppings[i]].calories;
};
return calories;
}
Hamburger.prototype.calculatePrice = function () {
var price = 0;
var arr = this.pricesAndCalorics;
price += arr[this.size].price;
price += arr[this.stuffing].price;
for (var i = 0; i < this.toppings.length; i++) {
price += arr[this.toppings[i]].price;
};
return price;
}
// маленький гамбургер с начинкой из сыра
var hamburger = new Hamburger(Hamburger.SIZE_SMALL, Hamburger.STUFFING_CHEESE);
// добавка из майонеза
hamburger.addTopping(Hamburger.TOPPING_MAYO);
// спросим сколько там калорий
console.log("Calories: %f", hamburger.calculateCalories());
// сколько стоит
console.log("Price: %f", hamburger.calculatePrice());
// я тут передумал и решил добавить еще приправу
hamburger.addTopping(Hamburger.TOPPING_SAUCE);
// А сколько теперь стоит?
console.log("Price with sauce: %f", hamburger.calculatePrice());
console.log("Calories with sauce: %f", hamburger.calculateCalories());