EasyJavaScriptTypeScript

useCounter Hook

ReactHooksState

Implement useCounter({ initial, min, max, step }) that returns
{ count, increment, decrement, reset, set }:

  • increment() — increase by step (default 1), clamp to max.
  • decrement() — decrease by step, clamp to min.
  • reset() — return to initial.
  • set(n) — set to n, clamped to [min, max].

solve(config, ops) drives the hook and returns count after each op.

Sample tests

Test #1Basic increment/decrement
Input: [{"initial":0},["increment","increment","decrement"]]
Output: [1,2,1]
Test #2Clamp at max
Input: [{"max":2,"initial":0},["increment","increment","increment"]]
Output: [1,2,2]
Test #3Step 2 and reset
Input: [{"step":2,"initial":5},["increment","decrement","reset"]]
Output: [7,5,5]
Test #4Clamp at min
Input: [{"min":-1,"initial":0},["decrement","decrement"]]
Output: [-1,-1]
Test #5set() then reset then increment
Input: [{"initial":3},[5,"reset","increment"]]
Output: [5,3,4]