Day 4 LeetCode challenge: Counter II - 30 days of JavaScript.
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.
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 itdecrement()reduces the current value by 1 and then returns itreset()sets the current value toinitand 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:
We defined the
createCounterfunction which takes in an integerinit.Inside the
createCounterfunction, we created acountvariable that will hold the current value of the counter.The
createCounterreturns an object with 3 functions: increment, decrement, and reset.The
incrementfunction increases thecountvalue by 1 and returns the updatedcountvalue.The
decrementfunction reduces thecountvalue by 1 and returns the updatedcountvalue.The
resetfunction sets thecountvalue to the default value.Finally, we called the
createCounterfunction. 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.

