Algorithm/LeetCode

[LeetCode] 2620. Counter : 클로저

그랴 2023. 11. 11. 14:00

문제

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).

 

정수 n이 주어질 때, counter 함수를 리턴하세요. 이 counter 함수는 초기에는 n을 리턴하며 이후에는 호출될 때마다 이전 값보다 1씩 큰 값을 리턴합니다.

 

 

예시

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.

 

 

풀이

/**
 * @param {number} n
 * @return {Function} counter
 */
var createCounter = function(n) {
    return function() {
        return n++
    };
};

/** 
 * const counter = createCounter(10)
 * counter() // 10
 * counter() // 11
 * counter() // 12
 */

createCounter 함수에 전달된 n을 내부의 익명의 함수가 접근하여 사용할 수 있다. (클로저)

 

관련 지식

클로저란, 함수가 속한 렉시컬 스코프를 기억하여, 함수가 렉시컬 스코프 밖에서 실행될 때도 그 스코프에 접근할 수 있게 하는 기능이다.