Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Cart Reducer

Reducershard

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 }`. An `add` action carries an `id`: increment the matching item's `qty`, or append `{ id, qty: 1 }` if it is not present. All updates immutable.

Sample tests

Input: cartReducer([], {"type":"add","id":1})
Output: [{"id":1,"qty":1}]
Input: cartReducer([{"id":1,"qty":1}], {"type":"add","id":1})
Output: [{"id":1,"qty":2}]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Mutating item.qty++ on the existing line.
  • Adding a duplicate line instead of incrementing the existing one.

Learning resources

  • React: useReducer
Approach & explanation (try first)

If the id is present, map produces a new array with that line's qty increased in a fresh object; if absent, spread a new { id, qty: 1 } onto the end. Either way the result is a new array.

Loading...
⌘/Ctrl + Enter

Run your code to see results.