Counter II - Problem

Imagine you have a digital counter with buttons to increment, decrement, and reset. Your task is to create a JavaScript function that simulates this behavior!

Write a function createCounter that accepts an initial integer init. It should return an object with three functions:

  • increment() - increases the current value by 1 and returns it
  • decrement() - reduces the current value by 1 and returns it
  • reset() - sets the current value back to init and returns it

This problem tests your understanding of closures, object methods, and state management in JavaScript. The counter should maintain its state between function calls and remember the original initialization value.

Example: If you create a counter with init = 5, calling increment() returns 6, decrement() returns 5, and reset() returns 5.

Input & Output

example_1.js โ€” Basic Operations
$ Input: init = 5 counter.increment() counter.reset() counter.decrement()
โ€บ Output: [6, 5, 4]
๐Ÿ’ก Note: Starting with 5: increment gives 6, reset returns to 5, decrement gives 4
example_2.js โ€” Negative Initial Value
$ Input: init = 0 counter.increment() counter.increment() counter.decrement() counter.reset()
โ€บ Output: [1, 2, 1, 0]
๐Ÿ’ก Note: Starting with 0: two increments reach 2, decrement gives 1, reset returns to 0
example_3.js โ€” Multiple Resets
$ Input: init = 1 counter.increment() counter.increment() counter.increment() counter.reset() counter.reset() counter.increment()
โ€บ Output: [2, 3, 4, 1, 1, 2]
๐Ÿ’ก Note: Multiple operations showing that reset always returns to the original init value

Constraints

  • -1000 โ‰ค init โ‰ค 1000
  • At most 1000 calls will be made to increment, decrement and reset
  • All operations should return the updated value

Visualization

Tap to expand
Counter State Machine VisualizationDigital Display5INCREMENT+1current++DECREMENT-1current--RESETโŸฒcurrent = initMemory (Closure)init = 5current = 5Operation ResultReturns: currentAfter operation๐ŸŽฏ Closure preserves both init and current values
Understanding the Visualization
1
Initialization
Counter is created with init=5, both initial and current values are set to 5
2
Increment Operation
Current value increases to 6, initial value remains 5 for future resets
3
Reset Operation
Current value is restored to the initial value (5)
4
Decrement Operation
Current value decreases to 4, demonstrating independent state management
Key Takeaway
๐ŸŽฏ Key Insight: JavaScript closures create a private scope that perfectly encapsulates state while providing controlled access through methods
Asked in
Meta 25 Google 20 Amazon 15 Microsoft 12
28.7K Views
Medium Frequency
~12 min Avg. Time
892 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