We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Counter II

Difficulty: Easy


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.


Code Solutions

// This function creates a counter object with methods to manipulate the count
function createCounter(init) {
    // Initialize current count to the initial value
    let current = init;

    return {
        // Increment method that increases current by 1 and returns it
        increment: function() {
            current += 1;
            return current;
        },
        // Decrement method that decreases current by 1 and returns it
        decrement: function() {
            current -= 1;
            return current;
        },
        // Reset method that sets current back to init and returns it
        reset: function() {
            current = init;
            return current;
        }
    };
}
← Back to All Questions