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 itdecrement()- reduces the current value by 1 and returns itreset()- sets the current value back toinitand 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
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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code