liveBook · Manning

Shopping cart

As explained in Grokking Simplicity

A collection associated with an online purchase that holds selected items and their quantities before checkout.

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

How Grokking Simplicity covers it

How deep it goes
Explains cart updates and reconstruction procedurally, while deferring deeper copying details to later treatment.
Examples
Uses shipping-icon logic, item-addition logs, duplicate products, quantities, prices, and cart-building callbacks.
What it assumes
Assumes basic JavaScript functions and arrays while teaching cart representation, quantities, and functional updates through examples.
What you can do after
Build it from scratch by reducing item logs into a cart and applying reusable, nonmutating item updates.
How it connects
Connects shopping carts with free shipping, immutable updates, reduce(), and abstraction barriers.

Also explained in

Compare how 2 books explain shopping cart →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Simplicity. The section links point to the parts of the book it draws on.