Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Todo Reducer (full)

Reducersmedium

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

Write a complete todo reducer driven by dispatched actions. Implement `todoReducer(state, action)` where state is an array of `{ text, done }`: - `{ type: 'add', text }` appends `{ text, done: false }`. - `{ type: 'toggle', index }` flips that todo's done. - `{ type: 'remove', index }` removes it. - `{ type: 'clearCompleted' }` drops all done todos. Unknown actions return the state unchanged. All updates immutable.

Examples

Input: add 'a', add 'b', toggle 0, remove 1
Output: [{ text: 'a', done: true }]
After adding a and b, toggling index 0 marks a done; removing index 1 drops b.

Sample tests

Input: add a, add b, toggle 0, remove 1
Output: [{"text":"a","done":true}]
Input: clearCompleted
Output: [{"text":"y","done":false}]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Mutating todos in place (push, t.done = ...) instead of returning new arrays/objects.

Learning resources

  • React: useReducer
Approach & explanation (try first)

A reducer is a pure (state, action) function. Each case builds new immutable state, which is exactly how useReducer expects updates.

Loading...
⌘/Ctrl + Enter

Run your code to see results.