Day 4 LeetCode challenge: Counter II - 30 days of JavaScript.
Table of contents
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 toinit
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:
We defined the
createCounter
function which takes in an integerinit
.Inside the
createCounter
function, we created acount
variable that will hold the current value of the counter.The
createCounter
returns an object with 3 functions: increment, decrement, and reset.The
increment
function increases thecount
value by 1 and returns the updatedcount
value.The
decrement
function reduces thecount
value by 1 and returns the updatedcount
value.The
reset
function sets thecount
value to the default value.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.
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.