Talentd
FleetCode

2665. Counter II

Easy80.5% acceptance3 companies

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 to init 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

Constraints:

  • -1000 <= init <= 1000
  • 0 <= calls.length <= 1000
  • calls[i] is one of "increment", "decrement" and "reset"

Asked at 3 companies

Hints open one at a time

Hint 1
You can return an object with methods.
Hint 2
Initialize a variable for currentCount. Inside these methods, add the appropriate logic which mutates currentCount.
7:26
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution

Similar problems

CounterEasy
Loading editor…
1/**
2 * @param {integer} init
3 * @return { increment: Function, decrement: Function, reset: Function }
4 */
5var createCounter = function(init) {
6
7};
8
9/**
10 * const counter = createCounter(5)
11 * counter.increment(); // 6
12 * counter.reset(); // 5
13 * counter.decrement(); // 4
14 */
Starter codeJavaScriptSpaces: 4
Examples
Input
5
["increment","reset","decrement"]
Input
0
["increment","increment","decrement","reset","reset"]
Your code is saved on this device.Solution