Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Counter Reducer

Reducerseasy

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

Implement `counterReducer(state, action)` where `state` is a number and `action.type` is `inc`, `dec`, or `reset`. Unknown actions return the state unchanged.

Sample tests

Input: counterReducer(0, {"type":"inc"})
Output: 1
Input: counterReducer(5, {"type":"dec"})
Output: 4

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Forgetting the default case, which would return undefined for unknown actions.
  • Mutating state instead of returning a new value.

Learning resources

  • React: useReducer
Approach & explanation (try first)

A reducer is a pure function from (state, action) to the next state. Each case computes a fresh value, and unknown actions fall through to return the state unchanged.

Loading...
⌘/Ctrl + Enter

Run your code to see results.