Problem Description
Write a function createCounter
. It should accept an initial integer init
. It should return an object with three functions: increment()
, decrement()
, and reset()
. The increment()
function increases the current value by 1 and returns it. The decrement()
function reduces the current value by 1 and returns it. The reset()
function sets the current value back to init
and returns it.
Key Insights
- The
createCounter
function needs to maintain a mutable state that tracks the current count. - Closure in JavaScript can be utilized to encapsulate the current count and the functions that modify it.
- Each of the three functions (
increment
,decrement
,reset
) directly manipulates this state.
Space and Time Complexity
Time Complexity: O(1) for each operation (increment, decrement, reset)
Space Complexity: O(1) for storing the current count and the initial value
Solution
The solution involves creating a counter object that maintains a current
value initialized to init
. The increment
, decrement
, and reset
functions are methods of this object. Each method directly modifies the current
value based on the specified operation and returns the updated value. This is efficiently achieved using closures to encapsulate the state.