Solving Leetcode 30 Days of JavaScript study plan problems
Problem:
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 toinit
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 JavaScript:
/**
* @param {integer} init
* @return { increment: Function, decrement: Function, reset: Function }
*/
function createCounter(init) {
const currentCount = init;
return {
increment: () => {
return ++init;
},
decrement: () => {
return --init;
},
reset: () => {
init = currentCount;
return init;
},
};
}
Initialize a variable for currentCount
to be the initial value of the counter before it's changed
Inside the createCounter
function, returns an object that has three properties increment
, decrement
, and reset
:
increment
: Holds a function that takes the current init value and increments it by onedecrement
: This function takes the current value of init decrements it by 1 and returns itreset
: This function sets init to be the currentCount. which was the first value before any increment and decrement.
This code essentially provides a simple way to perform these calculations in JavaScript code.