From 50e7f6c06c5670a63f78b002258f6e56bcd564b9 Mon Sep 17 00:00:00 2001 From: Ray C Date: Fri, 10 May 2024 14:08:58 +0800 Subject: [PATCH] Add cart functions --- src/app.js | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/app.js b/src/app.js index 8024b2c..22d368e 100644 --- a/src/app.js +++ b/src/app.js @@ -341,9 +341,29 @@ const cart = { storeName: 'cart-items', items: localStore.get(this.storeName) || [], addItem(item) { - this.items.push(item); + let isInCart = false; + for (const cartItem of this.items) + if (cartItem.name === item.name && cartItem.color === item.color) { + isInCart = true; + cartItem.num++; + break; + } + if (!isInCart) this.items.push({ ...item, num: 1 }); localStore.set(this.storeName, cart.items); }, + deleteItem(item) { + this.items.splice( + this.items.findIndex(cartItem => cartItem.name === item.name && cartItem.color === item.color), + 1 + ); + this.items.length + ? localStore.set(this.storeName, cart.items) + : localStore.remove(this.storeName); + }, + deleteAll() { + this.items.length = 0; + localStore.remove(this.storeName); + }, }; const user = {