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 }