Reputation: 23
My test app is almost complete, however when I remove an "apple" from the cart, and the quantity changes to 2, I can't seem to change the price/total amount from what is when it is three apples.
This may have to do with the constructor class, but I'm still relatively new to using it so I'm having a little trouble implementing a fix for this.
In the console log, I essentially want the total amount to reflect the quantity of apples ( which is now 2).
module.exports = {
shoppingCart: function () {
//create empty cart array
theCart = [];
// create two seperate versions of the same kind of object using class method
class Fruits {
constructor(fruit, price, quantity) {
this.fruit = fruit;
this.quantity = quantity;
this.price = price * quantity--;
}
}
let fruit1 = new Fruits("Apple", 4.95, 3); // create new object. sets the value of this
if (fruit1.quantity === 3) {
fruit1.quantity--;
}
let bothFruits = [fruit1];
//add items to the cart
Array.prototype.push.apply(theCart, bothFruits);
let total = fruit1.price + " = total amount.";
//function to add items to the cart
function removeAllItems() {
if (theCart.length = !0) {
theCart = [];
}
}
//removeAllItems();
console.log(theCart, total);
}
}
Upvotes: 0
Views: 229
Reputation: 63
It is better to define price
as unit price, not as total price. You can add more properties, for example cost
as the total price of fruit class. Then you can add a method to change the quantity of the fruit.
module.exports = {
shoppingCart: function () {
//create empty cart array
theCart = [];
// create two seperate versions of the same kind of object using class method
class Fruits {
constructor(fruit, price, quantity) {
this.fruit = fruit;
this.quantity = quantity;
this.price = price;
this.cost = quantity * price;
}
// add method to change fruit quantity
changeQuantity(newQuantity) {
this.quantity = newQuantity
this.cost = this.price * newQuantity;
}
}
let fruit1 = new Fruits("Apple", 4.95, 3); // create new object. sets the value of this
if (fruit1.quantity === 3) {
fruit1.quantity--;
fruit1.changeQuantity(fruit1.quantity); // call the method to change the quantity
}
let bothFruits = [fruit1];
//add items to the cart
Array.prototype.push.apply(theCart, bothFruits);
let total = fruit1.cost + " = total amount.";
//function to add items to the cart
function removeAllItems() {
if (theCart.length = !0) {
theCart = [];
}
}
//removeAllItems();
console.log(theCart, total);
}
}
result
[ Fruits { fruit: 'Apple', quantity: 2, price: 4.95, cost: 9.9 } ] 9.9 = total amount.
Upvotes: 1