Shopping Cart From Nothing

Implement a shopping cart. That is the whole brief. Pick how much of the derivation you want beside you.

I need XWhat is X?What must it remember?What can happen to it?What must always hold?ExamplesRepresent the stateWhich structure?Each operationPseudocodeImplement oneTest with examplesEdge casesIntegrate

The cart is the running example of the whole implementation track because it is small enough to hold in your head and rich enough to have rules — one entry per product, a quantity that is never zero, a total that is derived and never stored. Every mode below starts from “Implement a shopping cart.” and differs only in what is hidden.

Mode

The twelve stages, compact. Write at each, then see the reference.

0 / 12 stages attempted
stage 1 of 12

Define the concept

In one sentence, without any code: what is it? Then answer for yourself — does it have identity, who owns it, how long does it exist, should it survive a reload or a login?

Your attempt — write before you look

Shopping Cart = A temporary collection of products the user intends to purchase, held between browsing and checkout.

Identity, ownership, lifetime
  • Does a cart have identity? Yes, weakly. Two carts with the same items are still two carts, because each belongs to someone and will become a different order. It needs an id once it leaves memory; in memory the variable is the identity.
  • Who owns it? A shopper — a logged-in user or an anonymous session. The owner is part of the state because "my cart" has to be findable again.
  • How long does it exist? From the first add until checkout or abandonment. Whether it survives a reload, a closed browser or a login is not a property of the concept; it is a persistence decision made later, and each answer changes where the cart lives.
  • Should it survive reload? Usually yes for a store, usually no for a demo. V1 in memory says no; V2 browser storage says yes on one device; V3 server storage says yes everywhere the user is logged in.
  • Should it survive login? Only if an anonymous cart and a logged-in cart are merged — a rule that does not exist in V1 and appears as a modification later.
The principle
If you do not know how to build the thing, make the thing smaller until you reach something you do know how to build. Go one primitive lower →
SIMPLIFIED

Nothing here executes your code; the tests are shown, not run, and the check is whether you can explain each line against a rule. The reference is one derivation of one V1 — an array, in memory, one shopper — chosen for the size of a cart, not because a map would be wrong.