/** * Royal Red Bull - Cart Logic Manager * Handles persistent storage between index.html and cart.html */ // 1. Initialize cart by pulling from LocalStorage (browser memory) // If nothing is saved, start with an empty array [] let cart = JSON.parse(localStorage.getItem('cart_data')) || []; /** * Adds a product to the cart and saves it to memory * @param {Object} product - The product object from products.js */ function addToCart(product) { // Check if the item already exists in the cart using its ID const existingItem = cart.find(item => item.id === product.id); if (existingItem) { // If it exists, increase the quantity count existingItem.quantity = (existingItem.quantity || 1) + 1; } else { // If it's a new item, add it to the list with quantity 1 cart.push({ ...product, quantity: 1 }); } // Save the updated list to the browser's LocalStorage saveCart(); } /** * Saves the current cart array to LocalStorage as a string */ function saveCart() { localStorage.setItem('cart_data', JSON.stringify(cart)); } /** * Calculates the total number of items currently in the cart * @returns {number} Total quantity */ function getCartCount() { return cart.reduce((total, item) => total + (item.quantity || 1), 0); } /** * Clears the entire cart (Optional helper) */ function clearCart() { cart = []; localStorage.removeItem('cart_data'); }