(productId: number, quantity: number = 1)
| 54 | |
| 55 | // Add product to cart |
| 56 | function addToCart(productId: number, quantity: number = 1) { |
| 57 | // Check if product exists |
| 58 | if (!PRODUCTS[productId]) { |
| 59 | console.error("Product not found!"); |
| 60 | return false; |
| 61 | } |
| 62 | |
| 63 | // Check if enough stock |
| 64 | if (PRODUCTS[productId].stock < quantity) { |
| 65 | console.error("Not enough stock!"); |
| 66 | return false; |
| 67 | } |
| 68 | |
| 69 | // Check if product already in cart |
| 70 | let existingItem = false; |
| 71 | for (let i = 0; i < cartItems.length; i++) { |
| 72 | if (cartItems[i].productId === productId) { |
| 73 | // Update quantity |
| 74 | cartItems[i].quantity += quantity; |
| 75 | existingItem = true; |
| 76 | break; |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | // Add new item if not already in cart |
| 81 | if (!existingItem) { |
| 82 | cartItems.push({ |
| 83 | productId, |
| 84 | quantity, |
| 85 | price: PRODUCTS[productId].price, |
| 86 | }); |
| 87 | } |
| 88 | |
| 89 | // Update stock |
| 90 | PRODUCTS[productId].stock -= quantity; |
| 91 | |
| 92 | // Recalculate cart total |
| 93 | calculateCartTotal(); |
| 94 | |
| 95 | return true; |
| 96 | } |
| 97 | |
| 98 | // Remove product from cart |
| 99 | function removeFromCart(productId: number, quantity: number = 1) { |
no test coverage detected