2620. Counter
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 <= 10000 <= calls.length <= 1000calls[i] === "call"
Solution:
function createCounter(n: number): () => number {
return function() {
return n++;
}
}
/**
* const counter = createCounter(10)
* counter() // 10
* counter() // 11
* counter() // 12
*/
Closure(闭包)
n是createCounter的局部变量- 内层函数使用了
n,JS 会将它捕获,形成 closure - 即使
createCounter执行结束,n也不会被销毁
n++能记住状态,是因为闭包保存了私有变量n- 每次
createCounter调用都会生成独立的闭包环境
c1和c2互不影响
❌ 如果 n 是全局变量,所有 counter 会共享状态(不安全)
✅ 闭包 = 函数 + 外部变量环境(私有状态)
Js 特性
Java 中没有闭包, 用class使用