2665. Counter II
In this page, we will discuss LeetCode Problem 2665: Counter II. This problem asks you to implement a counter using closures and return an object with specific methods to increment, decrement, and reset the counter.
📄 Problem Statement
Write a function createCounter
that accepts an initial integer init
.
It should return an object with the following three functions:
increment()
: Increases the current value by 1 and returns it.decrement()
: Decreases the current value by 1 and returns it.reset()
: Resets the value back toinit
and returns it.
💡 Example
const counter = createCounter(5);
counter.increment(); // 6
counter.decrement(); // 5
counter.reset(); // 5
🧠 Explanation
The function uses closures to preserve the state of the counter across method calls.
By keeping a current
variable inside the outer function scope, each of the returned methods can modify and access this shared state safely.
✅ My Solution
/**
* @param {number} init
* @return {{
* increment: () => number,
* decrement: () => number,
* reset: () => number
* }}
*/
var createCounter = function(init) {
let current = init;
return {
increment: () => ++current,
decrement: () => --current,
reset: () => (current = init)
};
};