JSFiddle - React, Tailwind, and code Playground
JavaScript
function Item(name) {
this.name = name;
this.price = 0;
this.quantity = 0;
this.total = 0;
return this;
};
Item.prototype = {
setItemPrice: function(itemPrice) {
this.price = itemPrice;
return this;
},
setQuantity: function(itemUnit) {
this.quantity = itemUnit;
return this;
},
itemTotal: function() {
return this.total += this.price * this.quantity;
}
}
function Cart() {
this.items = [];
return this;
}
Cart.prototype = {
addItem: function (item) {
this.items.push(item);
return this;
},
removeItem: function (name) {
this.items = this.items.filter(function (item) {
return item.name !== name;
});
},
showCart: function () {
return this.items;
},
getCartTotal: function () {
return this.items.reduce(function (total, item) {
return total + (item.quantity * item.price);
}, 0);
}
}
const bag = new Item('BAG').setItemPrice(50).setQuantity(80);
const scarf = new Item('SCARF').setItemPrice(10).setQuantity(20);
const bead = new Item('BEAD').setItemPrice(1).setQuantity(120);
const candle = new Item('CANDLE').setItemPrice(20).setQuantity(5);
const cart = new Cart();
cart.addItem(bag).addItem(scarf).addItem(bead).addItem(candle);
console.log(cart.getCartTotal());
cart.removeItem('SCARF');
console.log(cart.getCartTotal());
console.log(cart.showCart());