Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Cart Reducer with Quantities

Reducersmedium

Course · Section 17: Modern JavaScript Development: Modules, Tooling, and Functional · Lecture 294: Declarative and Functional JavaScript Principles

Implement `cartReducer(state, action)` where state is an array of `{ id, qty }`: - `{ type: 'add', id }` increments qty or appends `{ id, qty: 1 }`. - `{ type: 'setQty', id, qty }` sets the quantity. - `{ type: 'remove', id }` removes the line. All immutable.

Examples

Input: add 1, add 1, add 2, setQty(1,5), remove 2
Output: [{ id: 1, qty: 5 }]
Item 1 is added then incremented then set to 5; item 2 is added then removed.

Sample tests

Input: add, increment, set, remove
Output: [{"id":1,"qty":5}]
Input: add new line
Output: [{"id":9,"qty":1}]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Mutating the matched line's qty in place.
  • Adding a duplicate line instead of incrementing.

Learning resources

  • React: useReducer
Approach & explanation (try first)

The reducer handles each cart action immutably, the pattern behind a useReducer-managed cart.

Loading...
⌘/Ctrl + Enter

Run your code to see results.