Day 4 LeetCode challenge: Counter II - 30 days of JavaScript.

Susan OdiiSusan Odii
2 min read

Welcome to day four of our 30 days of JavaScript series challenge. Today, we will be solving the Counter II challenge. The challenge says:

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.

Solution

/**
 * @param {integer} init
 * @return { increment: Function, decrement: Function, reset: Function }
 */
var createCounter = function (init) {
  let count = init;
  return {
    increment: function () {
      return ++count;
    },

    decrement: function () {
      return --count;
    },

    reset: function () {
      count = init;
      return count;
    },
  };
};

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

Explanation

Here is the step-by-step explanation of the code above:

  1. We defined the createCounter function which takes in an integer init.

  2. Inside the createCounter function, we created a count variable that will hold the current value of the counter.

  3. The createCounter returns an object with 3 functions: increment, decrement, and reset.

  4. The increment function increases the count value by 1 and returns the updated count value.

  5. The decrement function reduces the count value by 1 and returns the updated count value.

  6. The reset function sets the count value to the default value.

  7. Finally, we called the createCounter function. We also assigned it an initial value of 5.

Conclusion

This article solves the fourth LeetCode challenge in the series: 30 days of JavaScript. I look forward to sharing how I solved the day 5 challenge.

Happy Coding.

10
Subscribe to my newsletter

Read articles from Susan Odii directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Susan Odii
Susan Odii

Susan is a Frontend Web Developer. She is passionate about creating beautiful and engaging UI with good user experience. Susan is also a technical writer who writes on Frontend technologies to help other developers get a better understanding of a concept.