[Leetcode] JS 30 Counter II
Question 2665
arrow function/pre-increment operators/return object of functions
Question
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 toinitand 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
Constraints:
-1000 <= init <= 10000 <= calls.length <= 1000calls[i]is one of "increment", "decrement" and "reset"
My Solution
/**
* @param {integer} init
* @return { increment: Function, decrement: Function, reset: Function }
*/
var createCounter = function(init) {
var reset = init
var current = init
return {
increment: function() {
current += 1
return current
},
decrement: function() {
current -= 1
return current
},
reset: function() {
current = reset
return init
}
}
};
/**
* const counter = createCounter(5)
* counter.increment(); // 6
* counter.reset(); // 5
* counter.decrement(); // 4
*/
What Can Be Done Better
/**
* @param {integer} init
* @return { increment: Function, decrement: Function, reset: Function }
*/
var createCounter = function(init) {
let current = init;
return {
increment: () => ++current,
decrement: () => --current,
reset: () => (current = init),
};
};
Learning Points
- Arrow Functions: Shorter syntax for function declarations, reducing boilerplate while keeping the same functionality.
💡
More about arrow functions:
1. Concise Body (No Braces): If the function body is a single expression and doesn't use curly braces
2. Block Body (With Braces): If the function body uses curly braces
1. Concise Body (No Braces): If the function body is a single expression and doesn't use curly braces
{}, the value of that expression is implicitly returned.2. Block Body (With Braces): If the function body uses curly braces
{}, you must explicitly use the return keyword to return a value.- Avoid
resetVariable: Directly useinitfor resetting, sinceinitis already scoped within the closure. - Inline Return: Simplifies the increment and decrement methods using pre-increment (
++) and pre-decrement (--) operators.
Comments ()