2

Hamburger is complemented by one or more stuffing (not less than one).
However, when I use ...stuffing result is undefined.
Help me how to correct this task, so that it counts the cost of all the ingredients.

function Hamburger(size, ...stuffing) {
  this.size = size;
  this.stuffing = stuffing;
  this.topping = [];
}
Hamburger.small = {
  name: 'small',
  price: 10,
  kcal: 200
}
Hamburger.cheese = {
  name: 'cheese',
  price: 4,
  kcal: 10
}
Hamburger.meet = {
  name: 'meet',
  price: 40,
  kcal: 103
}
Hamburger.prototype.calculatePrice = () => {
  let allCost = humb1.size.price + humb1.stuffing.price;
  return `Total burger price: ${allCost}`
}

let humb1 = new Hamburger(Hamburger.small, Hamburger.cheese, Hamburger.meet);
console.log(humb1.calculatePrice());
Maor Refaeli
  • 2,417
  • 2
  • 19
  • 33
Igor Shvets
  • 547
  • 6
  • 15
  • 1
    `stuffing` is an array. It doesn't have a `.price` property. If you want the cost of *all* ingredients, you will have to sum them. Use a loop, or `.reduce()` – Bergi Sep 30 '18 at 18:02

1 Answers1

3
  • You can't use arrow function they way you used, you need to use the good old function declaration instead (or use es6 class syntactic-sugar as well). Have a look at this answer to understand why (in your case instead of getting the Hamburger object you get the global window object).
  • Don't use humb1 on the implementation of calculatePrice which is a function that is part of the class prototype while humb1 is a class instance.
  • stuffing is an array. You need to work on each item to get the total cost. I used reduce here.

function Hamburger(size, ...stuffing) {
  this.size = size;
  this.stuffing = stuffing;
  this.topping = [];
}
Hamburger.small = {
  name: 'small',
  price: 10,
  kcal: 200
}
Hamburger.cheese = {
  name: 'cheese',
  price: 4,
  kcal: 10
}
Hamburger.meet = {
  name: 'meet',
  price: 40,
  kcal: 103
}
Hamburger.prototype.calculatePrice = function() {
  let totalCost = this.size.price + this.stuffing.reduce((a, c) => a + c.price, 0);
  return `Total burger price: ${totalCost}`;
}

let humb1 = new Hamburger(Hamburger.small, Hamburger.cheese, Hamburger.meet);
console.log(humb1.calculatePrice());
Maor Refaeli
  • 2,417
  • 2
  • 19
  • 33