JavaScriptFundamental (ES6), part 1
Immutable reducer for a shopping cart in JavaScript
117 an immutable reducer for a market cart
fairWrite reduce(state, action) for a cart that handles add, drop, qty and note without ever writing to the state it was given. Adding a SKU already in the cart must merge quantities rather than append a second row, and qty: 0 must mean drop. Prove the starting state is untouched, that an unknown action returns the very same object, and that only the parts that changed were rebuilt.
Stuck? Three hints, smallest first
- 1. Every branch ends in
{ ...state, items: something }. Nopush, nosplice, no assignment to a property ofstate. - 2. To bump one row,
mapthe array and spread only the matching item: the others come out as the same objects. - 3. A branch that changes nothing should
return stateitself, not a copy — that is what lets a consumer compare with===.
const empty = Object.freeze({ items: [], note: '' });
const reduce = (state, action) => {
switch (action.type) {
case 'add': {
const seen = state.items.some((i) => i.sku === action.sku);
const items = seen
? state.items.map((i) => (i.sku === action.sku ? { ...i, qty: i.qty + action.qty } : i))
: [...state.items, { sku: action.sku, name: action.name, qty: action.qty, kobo: action.kobo }];
return { ...state, items };
}
case 'drop':
return { ...state, items: state.items.filter((i) => i.sku !== action.sku) };
case 'qty':
return action.qty > 0
? { ...state, items: state.items.map((i) => (i.sku === action.sku ? { ...i, qty: action.qty } : i)) }
: reduce(state, { type: 'drop', sku: action.sku });
case 'note':
return { ...state, note: action.text };
default:
return state;
}
};
const feed = (state, actions) => actions.reduce(reduce, state);
const totalKobo = (state) => state.items.reduce((sum, i) => sum + i.qty * i.kobo, 0);
const stocked = feed(empty, [
{ type: 'add', sku: 'GARRI-5', name: 'Garri, 5kg', qty: 2, kobo: 450000 },
{ type: 'add', sku: 'PALM-1', name: 'Palm oil, 1L', qty: 1, kobo: 320000 },
{ type: 'add', sku: 'GARRI-5', qty: 1 },
]);
const noted = reduce(stocked, { type: 'note', text: 'Leave it at the gate' });
const zeroed = reduce(stocked, { type: 'qty', sku: 'PALM-1', qty: 0 });
const ignored = reduce(stocked, { type: 'sing' });
let frozenWrite = 'no error';
try { empty.note = 'hijacked'; } catch (e) { frozenWrite = e.constructor.name; }
console.log('cart :', stocked.items.map((i) => `${i.name} x${i.qty}`));
console.log('total :', totalKobo(stocked), 'kobo');
console.log('shared:', noted.items === stocked.items, '| same object back:', ignored === stocked);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('three adds, two rows, because the repeat merged', stocked.items.map((i) => [i.sku, i.qty]), [['GARRI-5', 3], ['PALM-1', 1]]);
test('the merge kept the name and price from the first add', stocked.items[0].name, 'Garri, 5kg');
test('the total reads the rebuilt rows', totalKobo(stocked), 1670000);
test('a quantity of zero is a removal', zeroed.items.map((i) => i.sku), ['GARRI-5']);
test('and the state we started from never changed', [empty.items.length, empty.note], [0, '']);
test('an action nobody handles gives back the identical object', ignored === stocked, true);
test('changing the note rebuilt the wrapper and reused the rows', [noted !== stocked, noted.items === stocked.items], [true, true]);
test('under strict mode a write to the frozen start throws', frozenWrite, 'TypeError');
test('though the array inside it was never frozen at all', Object.isFrozen(empty.items), false);
Two rules make a reducer safe to hand to a UI. Never write to the argument, and return the argument itself when nothing changed. The second is what makes the cheap comparison work: a consumer can skip re-rendering a list when next.items === prev.items, and that is only true if the branch that changed the note left the array alone. Spread gives you that for free — it copies one level, so untouched rows come through as the same objects.
qty: 0 delegating to drop is worth copying. Calling the reducer from inside itself keeps one definition of what removal means, so a later change to drop cannot leave the two paths disagreeing.
Object.freeze on the starting state is a seatbelt, and only for the top level: the assignment throws under strict mode, but empty.items is a plain array that push would happily mutate. Freezing tells you about your own mistakes early; it is not a deep guarantee.