I'm currently working with a Cart object in Javascript and I need to check if a specific item is present in the cart. Here's my approach:
- If the item is already in the cart, update its quantity.
- If it's not in the cart, add it to the items array.
This is how I've implemented it:
let item = {id: this.id, name: this.name, price: this.price, amount: this.amount}
let isItemPresent = false;
this.cart.items.forEach(element => {
if (element.id === item.id) {
element.amount += item.amount;
isItemPresent = true;
}
})
if (!isItemPresent) {
this.cart.items.push(item);
}
While this solution works fine for me, I'm curious if there might be a faster or more efficient way of accomplishing this task. Any suggestions on optimization?