Counter 2 | #2665 | LeetCode Solution

Author: neptune | 04th-Sep-2023

Problem : Counter 2 | #2665 | LeetCode

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

The three functions are:

1. increment() increases the current value by 1 and then returns it.

2. decrement() reduces the current value by 1 and then returns it.

3. reset() sets the current value to init and then returns it.


Example 1:

Input: init = 5, calls = ["increment","reset","decrement"]

Output: [6,5,4]

Explanation:

const counter = createCounter(5);

counter.increment(); // 6

counter.reset(); // 5

counter.decrement(); // 4


Example 2:

Input: 

init = 0, calls = ["increment", "increment", "decrement", "reset", "reset"]

Output: [1,2,1,0,0]

Explanation:

const counter = createCounter(0);

counter.increment(); // 1

counter.increment(); // 2

counter.decrement(); // 1

counter.reset(); // 0

counter.reset(); // 0


Solution:

    /**

     * @param {integer} init

     * @return { increment: Function, decrement: Function, reset: Function }

     */

    var createCounter = function(init) {

        var current = init;

        return {

            increment: function() {

                current += 1;

                return current;

            },

            decrement: function() {

                current -= 1;

                return current;

            },

            reset: function() {

                current = init;

                return current;

            }

        }

    };

    /**

     * const counter = createCounter(5)

     * counter.increment(); // 6

     * counter.reset(); // 5

     * counter.decrement(); // 4

     */


Explanation:

Here's an explanation of the code step by step:


1. We define the `createCounter` function, which takes an initial integer `init` as a parameter.


2. Inside the `createCounter` function, we create a variable `current` and set it to the initial value `init`. This variable will hold the current value of the counter.


3. We return an object with three functions: `increment`, `decrement`, and `reset`.


4. The `increment` function increases the `current` value by 1 and then returns the updated `current` value.


5. The `decrement` function reduces the `current` value by 1 and then returns the updated `current` value.


6. The `reset` function sets the `current` value back to the initial value `init` and then returns the updated `current` value.


7. Finally, we demonstrate the usage of the `createCounter` function by creating a counter with an initial value of 5 and calling the three functions on it, printing the results to the console.