Ömer Şengül

createShoppingCart

byÖmer ŞengülCreated February 25, 2026 at 04:51 PM
createShoppingCart
1const createShoppingCart = () => {
2  let items = [];
3
4  const addItem = (name, price, quantity = 1) => {
5    const existing = items.find((i) => i.name === name);
6    if (existing) {
7      items = items.map((i) =>
8        i.name === name ? { ...i, quantity: i.quantity + quantity } : i
9      );
10    } else {
11      items = [...items, { name, price, quantity }];
12    }
13  };
14
15  const removeItem = (name) => {
16    items = items.filter((i) => i.name !== name);
17  };
18
19  const updateQuantity = (name, quantity) => {
20    if (quantity <= 0) return removeItem(name);
21    items = items.map((i) => (i.name === name ? { ...i, quantity } : i));
22  };
23
24  const getTotal = () =>
25    items.reduce((acc, i) => acc + i.price * i.quantity, 0);
26
27  const applyDiscount = (percent) => {
28    const total = getTotal();
29    const discount = total * (percent / 100);
30    return +(total - discount).toFixed(2);
31  };
32
33  const getItems = () => items;
34
35  const clear = () => {
36    items = [];
37  };
38
39  return { addItem, removeItem, updateQuantity, getTotal, applyDiscount, getItems, clear };
40};
41
42// Kullanım
43const cart = createShoppingCart();
44
45cart.addItem("Keyboard", 49.99, 1);
46cart.addItem("Mouse", 29.99, 2);
47cart.addItem("Keyboard", 49.99, 1); // quantity 2 olur
48
49cart.updateQuantity("Mouse", 1);
50
51console.log(cart.getItems());
52console.log("Total:", cart.getTotal());
53console.log("After 10% discount:", cart.applyDiscount(10));
54
55cart.removeItem("Keyboard");
56console.log("After remove:", cart.getItems());

Description

A simple shopping cart built with closure pattern. Supports adding, removing, and updating item quantities, along with total price calculation and discount application.

Discussion (0)

Sort by: