summaryrefslogtreecommitdiff
path: root/src/helpers/cart.js
blob: 07e47324e1ac274dfa7ed88776095dc8689f60ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const getCart = () => {
  const cart = localStorage.getItem('cart');
  if (cart) return JSON.parse(cart);
  return [];
}

const setCart = (cart) => {
  localStorage.setItem('cart', JSON.stringify(cart));
  return true;
}

const getItemIndex = (product_id) => {
  const cart = getCart();
  return cart.findIndex((item) => item.product_id == product_id);
}

const addToCart = (product_id, quantity) => {
  let cart = getCart();
  let itemIndexByProductId = getItemIndex(product_id);
  if (itemIndexByProductId > -1) {
    updateItemCart(product_id, quantity);
  } else {
    cart.push({ product_id, quantity });
  }
  setCart(cart);
  return true;
}

const deleteItemCart = (product_id) => {
  let cart = getCart();
  let itemIndexByProductId = getItemIndex(product_id);
  if (itemIndexByProductId > -1) {
    cart.splice(itemIndexByProductId, 1)
  }
  setCart(cart);
  return true;
}

const updateItemCart = (product_id, quantity) => {
  let cart = getCart();
  let itemIndexByProductId = getItemIndex(product_id);
  if (itemIndexByProductId > -1) {
    cart[itemIndexByProductId].quantity += quantity;
  }
  setCart(cart);
  return true;
}

export {
  getCart,
  addToCart,
  deleteItemCart,
  updateItemCart
}