A shopping cart is a primary e-commerce entity that holds selected items and quantities before checkout. Treating business actions as cart operations aligns code with business requirements: free-shipping checks receive a cart, calculate its total, and return whether it reaches 20. section 5.2
A functional cart design emphasizes:
- Adding an item returns a modified copy instead of changing the existing cart. section 5.2
- Small, cohesive calculations improve understanding, reuse, testing, and later maintenance. section 5.2
- A list of logged item additions can be reduced into the current cart, incrementing quantities for duplicates. section 13.15
Rebuilding a lost cart
Given ["shirt", "shoes", "shirt", "socks"], reduce the list from an empty object. Add missing items with quantity 1; for existing items, return a cart whose quantity increases by 1. Extract this callback as addOne when the operation deserves a reusable API. section 13.15
var shoppingCart = reduce(itemsAdded, {}, addOne); #1
function addOne(cart, item) { #2
if(!cart[item])
return add_item(cart, {name: item, quantity: 1, price:
priceLookup(item)});
else {
var quantity = cart[item].quantity;
return setFieldByName(cart, item, ‘quantity’, quantity + 1);
}
}
Shows the reusable reduce callback that builds a cart while preserving the duplicate-item rule. section 13.15

