MCPcopy Create free account
hub / github.com/SuperSimpleDev/javascript-course / Cart

Class Cart

2-copy-of-code/lesson-18/data/cart-class.js:1–79  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected