diff options
Diffstat (limited to 'src/helpers')
| -rw-r--r-- | src/helpers/cart.js | 39 |
1 files changed, 13 insertions, 26 deletions
diff --git a/src/helpers/cart.js b/src/helpers/cart.js index 07e47324..8712c03a 100644 --- a/src/helpers/cart.js +++ b/src/helpers/cart.js @@ -1,7 +1,7 @@ const getCart = () => { const cart = localStorage.getItem('cart'); if (cart) return JSON.parse(cart); - return []; + return {}; } const setCart = (cart) => { @@ -9,18 +9,18 @@ const setCart = (cart) => { return true; } -const getItemIndex = (product_id) => { - const cart = getCart(); - return cart.findIndex((item) => item.product_id == product_id); +const getItemCart = (product_id) => { + let cart = getCart(); + return cart[product_id]; } -const addToCart = (product_id, quantity) => { +const createOrUpdateItemCart = (product_id, quantity) => { let cart = getCart(); - let itemIndexByProductId = getItemIndex(product_id); - if (itemIndexByProductId > -1) { - updateItemCart(product_id, quantity); + let isFoundInCart = cart[product_id]; + if (isFoundInCart) { + cart[product_id].quantity = quantity; } else { - cart.push({ product_id, quantity }); + cart[product_id] = { product_id, quantity }; } setCart(cart); return true; @@ -28,27 +28,14 @@ const addToCart = (product_id, quantity) => { 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; - } + delete cart[product_id] setCart(cart); return true; } export { getCart, - addToCart, - deleteItemCart, - updateItemCart + getItemCart, + createOrUpdateItemCart, + deleteItemCart }
\ No newline at end of file |
