Reputation: 63
I built two classes, a product with name and price and a shopping cart for an array of products; for the ShoppingCart get totPrice method I'm using the reduce() function on the array cart of the constructor, but I'm always getting the error above and I don't get why.
class Product {
constructor(name,price) {
this.name = name;
this.price = price;
}
toString() {
console.log(this.name + ' - ' + this.price);
}
}
class ShoppingCart {
constructor(cart) {
this.cart = cart;
}
get totPrice() {
return this.cart.reduce((el1,el2) => {el1.price + el2.price});
}
addProd = function(prod) {
this.cart.push(prod);
this.cart.totPrice += prod.price;
if(this.cart.length >= 5){
this.totPrice = this.totPrice * 0.9;
}
if(this.cart.filter(tmp => tmp.name === prod.name).length % 4 === 0){
this.totPrice -= prod.price;
}
}
removeProd = function(prod) {
let i = this.cart.findIndex(el => {prod.name === el.name});
this.cart.splice(i,1);
console.log(`The product ${prod.name} has been removed from your shopping cart`);
}
}
let prod1 = new Product('Apple',15);
let prod2 = new Product('Banana',20);
let prod3 = new Product('Melon',25);
let shopCart = new ShoppingCart([prod1,prod2,prod3]);
console.log(shopCart.totPrice);
Upvotes: 0
Views: 178
Reputation: 58
There is already an answer for this one explained here.
After the first iteration your're returning a number and then trying to get property sum.price of it to add it to the next object which is undefined. Also you need a initial value for the sum.
get totPrice() {
return this.cart.reduce((acc,el) => acc + el.price,0);
}
Upvotes: 1