| 1 | function Cart(localStorageKey) { |
| 2 | const cart = { |
| 3 | cartItems: undefined, |
| 4 | |
| 5 | loadFromStorage() { |
| 6 | this.cartItems = JSON.parse(localStorage.getItem(localStorageKey)); |
| 7 | |
| 8 | if (!this.cartItems) { |
| 9 | this.cartItems = [{ |
| 10 | productId: 'e43638ce-6aa0-4b85-b27f-e1d07eb678c6', |
| 11 | quantity: 2, |
| 12 | deliveryOptionId: '1' |
| 13 | }, { |
| 14 | productId: '15b6fc6f-327a-4ec4-896f-486349e85a3d', |
| 15 | quantity: 1, |
| 16 | deliveryOptionId: '2' |
| 17 | }]; |
| 18 | } |
| 19 | }, |
| 20 | |
| 21 | saveToStorage() { |
| 22 | localStorage.setItem(localStorageKey, JSON.stringify(this.cartItems)); |
| 23 | }, |
| 24 | |
| 25 | addToCart(productId) { |
| 26 | let matchingItem; |
| 27 | |
| 28 | this.cartItems.forEach((cartItem) => { |
| 29 | if (productId === cartItem.productId) { |
| 30 | matchingItem = cartItem; |
| 31 | } |
| 32 | }); |
| 33 | |
| 34 | if (matchingItem) { |
| 35 | matchingItem.quantity += 1; |
| 36 | } else { |
| 37 | this.cartItems.push({ |
| 38 | productId: productId, |
| 39 | quantity: 1, |
| 40 | deliveryOptionId: '1' |
| 41 | }); |
| 42 | } |
| 43 | |
| 44 | this.saveToStorage(); |
| 45 | }, |
| 46 | |
| 47 | removeFromCart(productId) { |
| 48 | const newCart = []; |
| 49 | |
| 50 | this.cartItems.forEach((cartItem) => { |
| 51 | if (cartItem.productId !== productId) { |
| 52 | newCart.push(cartItem); |
| 53 | } |
| 54 | }); |
| 55 | |
| 56 | this.cartItems = newCart; |
| 57 | |
| 58 | this.saveToStorage(); |
| 59 | }, |
| 60 | |