Skip to content
Counter II - 2665

Counter II – 2665

🔗LC2665 🟢 Easy 🧩 Pattern – Closures

📅 Day 4/30 Days of JavaScript

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

The three functions are:

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

Example

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

Solution

We return an object with the three required functions as properties, we implement a closure to manipulate the values that are required.

/**
 * @param {integer} init
 * @return { increment: Function, decrement: Function, reset: Function }
 */
var createCounter = function (init) {
    const firstValue = init;
    return {
        increment: () => ++init,
        decrement: () => --init,
        reset: () => {
            init = firstValue
            return init
        }
    }
};

/**
 * const counter = createCounter(5)
 * counter.increment(); // 6
 * counter.reset(); // 5
 * counter.decrement(); // 4
 */
Back to Top