Overview
Build the two helpers behind every online shop's basket: add a product without mutating the cart, and compute the amount to pay.
- Return a new array instead of changing the old one
- Copy an object before changing a field
- reduce for totals
Short Course
An immutable cart is never edited: each change returns a new cart. Trap:
copying the array isn't enough — line.qty += 1 would still change the old
line, so copy it with { ...line }.
const cart = [{ id: "pen", qty: 1 }];
const next = cart.map(line =>
line.id === "pen" ? { ...line, qty: line.qty + 1 } : line
);
cart[0].qty; // 1 — untouched
next[0].qty; // 2
Task
Write addItem(cart, item), which returns a new cart where an existing id
gets its qty increased and a new one is added at the end, and total(cart),
the sum of price * qty (0 for an empty cart).
Test Suites
Pending
Next
Output