I am trying to remove an item without removing the cart and reducing a price if the customer has a coupon or exceeds a certain quantity while js before using Django here is the html code js if you have any advice do not hesitate
html
<div data-name="name" data-price="250" data-id="2">
<img src="x.jpg" alt="" />
<h3>name</h3>
<input type="number" class="count" value="1" />
<button class="tiny">Add to cart</button>
</div>
<script type="text/template" id="cartT">
<% _.each(items, function (item) { %> <div class = "panel"> <h3> <%= item.name %> </h3> <span class="label">
<%= item.count %> piece<% if(item.count > 1)
{%>s
<%}%> for <%= item.total %>$</span > </div>
<% }); %>
</script>
js
addItem: function (item) {
if (this.containsItem(item.id) === false) {
this.items.push({
id: item.id,
name: item.name,
price: item.price,
count: item.count,
total: item.price * item.count
});
storage.saveCart(this.items);
} else {
this.updateItem(item);
}
this.total += item.price * item.count;
this.count += item.count;
helpers.updateView();
},
containsItem: function (id) {
if (this.items === undefined) {
return false;
}
for (var i = 0; i < this.items.length; i++) {
var _item = this.items[i];
if (id == _item.id) {
return true;
}
}
return false;
},
updateItem: function (object) {
for (var i = 0; i < this.items.length; i++) {
var _item = this.items[i];
if (object.id === _item.id) {
_item.count = parseInt(object.count) + parseInt(_item.count);
_item.total = parseInt(object.total) +parseInt(_item.total);
this.items[i] = _item;
storage.saveCart(this.items);
}
}
}
You can use the filter function to remove an item, this way you are going to remove only the item that contains a specific id.
removeItem(id) {
this.items = this.items.filter(item => item.id !== id);
}
To apply the coupon, unless you have all the coupons stored in your front-end, you should make an HTTPS call to check if the coupon is valid or not, but also its value to then apply the discount at the cart.
A suggestion to your code is related to containsItem function, where you iterate through the entire array and check every item id individually, and then return to the user. You can use the function some to let JS check it for you.
containsItem: function (id) {
return this.items?.some(item => item.id === id);
}
//PS: the ?. is a notion that checks if the variable exists and if it's true it continues, that way you won't have an undefined error. It is called [Optional Chaining][2]
Another suggestion is on the updateItem, you can get the element that you need with the find function.
updateItem: function (object) {
const itemToUpdate = this.items.find(item => item.id === object.id);
if(itemToUpdate) {
itemToUpdate.count = parseInt(object.count) + parseInt(itemToUpdate.count);
itemToUpdate.total = parseInt(object.total) +parseInt(itemToUpdate.total);
storage.saveCart(this.items);
}
}
Also, you don't need to reassign the array, since when you refer to the object, it will be updated on its source as well.