Talentd
FleetCode

2620. Counter

Easy81.6% acceptance6 companies

Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (n, n + 1, n + 2, etc).

Example 1:

Input: 
n = 10 
["call","call","call"]
Output: [10,11,12]
Explanation: 
counter() = 10 // The first time counter() is called, it returns n.
counter() = 11 // Returns 1 more than the previous time.
counter() = 12 // Returns 1 more than the previous time.

Example 2:

Input: 
n = -2
["call","call","call","call","call"]
Output: [-2,-1,0,1,2]
Explanation: counter() initially returns -2. Then increases after each sebsequent call.

Constraints:

  • -1000 <= n <= 1000
  • 0 <= calls.length <= 1000
  • calls[i] === "call"

Hints open one at a time

Hint 1
In JavaScript, a function can return a closure. A closure is defined as a function and the variables declared around it (it's lexical environment).
Hint 2
A count variable can be initialized in the outer function and mutated in the inner function.
5:08
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1/**
2 * @param {number} n
3 * @return {Function} counter
4 */
5var createCounter = function(n) {
6
7 return function() {
8
9 };
10};
11
12/**
13 * const counter = createCounter(10)
14 * counter() // 10
15 * counter() // 11
16 * counter() // 12
17 */
Starter codeJavaScriptSpaces: 4
Examples
Input
10
["call","call","call"]
Input
-2
["call","call","call","call","call"]
Your code is saved on this device.Solution