Counter II - Problem
Write a function createCounter that accepts an initial integer init and returns an object with three functions.
The three functions are:
- increment() increases the current value by 1 and then returns it.
- decrement() reduces the current value by 1 and then returns it.
- reset() sets the current value to
initand then returns it.
Input & Output
Example 1 — Basic Counter Operations
$
Input:
init = 5, calls = ["increment", "increment", "decrement", "reset", "reset"]
›
Output:
[6,7,6,5,5]
💡 Note:
Starting with 5: increment() → 6, increment() → 7, decrement() → 6, reset() → 5, reset() → 5
Example 2 — Starting from Zero
$
Input:
init = 0, calls = ["increment", "increment", "decrement", "reset", "reset"]
›
Output:
[1,2,1,0,0]
💡 Note:
Starting with 0: increment() → 1, increment() → 2, decrement() → 1, reset() → 0, reset() → 0
Example 3 — Negative Initial Value
$
Input:
init = -2, calls = ["reset", "increment", "decrement"]
›
Output:
[-2,-1,-2]
💡 Note:
Starting with -2: reset() → -2, increment() → -1, decrement() → -2
Constraints
- -1000 ≤ init ≤ 1000
- At most 1000 calls will be made to increment, decrement and reset
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code