Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Todos Reducer

Reducersmedium

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

Implement `todosReducer(state, action)` where `state` is an array of `{ id, text, done }`. Handle `{ type: 'add', todo }` (append), `{ type: 'toggle', id }` (flip that todo's `done`), and `{ type: 'remove', id }` (delete it). Unknown actions return state unchanged.

Sample tests

Input: todosReducer([], {"type":"add","todo":{"id":1,"text":"a","done":false}})
Output: [{"id":1,"text":"a","done":false}]
Input: todosReducer([{"id":1,"text":"a","done":false}], {"type":"toggle","id":1})
Output: [{"id":1,"text":"a","done":true}]

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Mutating a todo (t.done = !t.done) changes state in place; spread it into a new object instead.
  • Forgetting the default branch returns undefined for unknown actions.

Learning resources

  • React: useReducer
Approach & explanation (try first)

A list reducer derives the next array from the current one. add appends immutably, toggle maps to a new array flipping one item via an object spread, and remove filters it out. Unknown actions fall through unchanged.

Loading...
⌘/Ctrl + Enter

Run your code to see results.