Initial commit
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
const Cart = (function () {
|
||||
const STORAGE_KEY = "cart";
|
||||
const TAX_RATE = 0.05;
|
||||
let couponDiscount = 0;
|
||||
|
||||
// ─────────────────────────────
|
||||
// Internal
|
||||
// ─────────────────────────────
|
||||
function getCart() {
|
||||
return JSON.parse(localStorage.getItem(STORAGE_KEY)) || [];
|
||||
}
|
||||
|
||||
function saveCart(cart) {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(cart));
|
||||
window.dispatchEvent(new Event("cartUpdated"));
|
||||
}
|
||||
|
||||
function findItem(cart, id) {
|
||||
return cart.find((item) => item.id === id);
|
||||
}
|
||||
|
||||
// ─────────────────────────────
|
||||
// Public API
|
||||
// ─────────────────────────────
|
||||
|
||||
function addItem(product, quantity = 1) {
|
||||
const cart = getCart();
|
||||
const existing = findItem(cart, product.id);
|
||||
|
||||
if (existing) {
|
||||
existing.quantity += quantity;
|
||||
} else {
|
||||
cart.push({
|
||||
id: product.id,
|
||||
name: product.basic.name,
|
||||
price: product.pricing.price,
|
||||
image: product.media.mainImage,
|
||||
quantity,
|
||||
});
|
||||
}
|
||||
|
||||
saveCart(cart);
|
||||
}
|
||||
|
||||
function removeItem(id) {
|
||||
const cart = getCart().filter((item) => item.id !== id);
|
||||
saveCart(cart);
|
||||
}
|
||||
|
||||
function updateQuantity(id, quantity) {
|
||||
const cart = getCart();
|
||||
const item = findItem(cart, id);
|
||||
if (!item) return;
|
||||
|
||||
item.quantity = Math.max(1, quantity);
|
||||
saveCart(cart);
|
||||
}
|
||||
|
||||
function clear() {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
window.dispatchEvent(new Event("cartUpdated"));
|
||||
}
|
||||
|
||||
function applyCoupon(code) {
|
||||
if (code === "MEDI10") {
|
||||
couponDiscount = 0.1;
|
||||
window.dispatchEvent(new Event("cartUpdated"));
|
||||
return true;
|
||||
}
|
||||
|
||||
couponDiscount = 0;
|
||||
window.dispatchEvent(new Event("cartUpdated"));
|
||||
return false;
|
||||
}
|
||||
|
||||
function getTotals() {
|
||||
const cart = getCart();
|
||||
|
||||
const subtotal = cart.reduce(
|
||||
(sum, item) => sum + item.price * item.quantity,
|
||||
0
|
||||
);
|
||||
|
||||
const tax = subtotal * TAX_RATE;
|
||||
const discount = subtotal * couponDiscount;
|
||||
const total = subtotal - discount;
|
||||
|
||||
return {
|
||||
subtotal,
|
||||
tax,
|
||||
discount,
|
||||
total,
|
||||
};
|
||||
}
|
||||
|
||||
function getTotalCount() {
|
||||
return getCart().reduce((sum, item) => sum + item.quantity, 0);
|
||||
}
|
||||
|
||||
return {
|
||||
getCart,
|
||||
addItem,
|
||||
removeItem,
|
||||
updateQuantity,
|
||||
clear,
|
||||
applyCoupon,
|
||||
getTotals,
|
||||
getTotalCount,
|
||||
};
|
||||
})();
|
||||
Reference in New Issue
Block a user