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 init and 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
Counter II - Class-Based Implementation INPUT init = 5 Function Calls: "increment" "increment" "decrement" "reset" "reset" 0: 1: 2: 3: 4: 5 calls to process ALGORITHM STEPS 1 Create Counter Class Store init and current class Counter { this.init = init this.current = init } 2 increment() return ++this.current 3 decrement() return --this.current 4 reset() current = init; return it Execution Trace: 5 --inc--> 6 --inc--> 7 7 --dec--> 6 6 --reset--> 5 --reset--> 5 FINAL RESULT Output Array: 6 inc 7 inc 6 dec 5 reset 5 reset [6, 7, 6, 5, 5] OK - Verified All 5 calls processed correctly Key Insight: The class-based approach uses encapsulation to store both 'init' (original value) and 'current' (working value). This allows reset() to restore the original value while increment/decrement modify current. Closure preserves state between calls. TutorialsPoint - Counter II | Class-Based Implementation
Asked in
Google 15 Facebook 12
23.4K Views
Medium Frequency
~10 min Avg. Time
876 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen