게으른개발너D

[Function, Closure] Counter ⭐️ 본문

알고리즘/과제

[Function, Closure] Counter ⭐️

lazyhysong 2023. 7. 3. 18:12

https://leetcode.com/problems/counter/

 

Counter - LeetCode

Can you solve this real interview question? 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).  

leetcode.com

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
  • At most 1000 calls to counter() will be made

 

solution

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

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

solution2

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

 

 

 

typescript

function createCounter(n: number): () => number {
    let count = n;
    return function() {
        return count++;
    }
}


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

solution에 대한 설명

1. closure concept

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

 

Closures - JavaScript | MDN

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closur

developer.mozilla.org

클로저는 함수와 함수가 선언된 어휘적 환경의 조합이다. 함수가 다른 함수 안에서 정의되고, 내부 함수가 외부 함수의 범위에 있는 변수를 참조한다.

내부 함수가 외부 함수에 의해서 반환될 때 외부 함수의 범위를 유지하며 외부 함수 실행이 완료된 후에도 이러한 변수에 계속 액세스할 수 있다.

클로저는 외부 함수의 스코프에서 값을 "기억"하고 나중에 사용할 수 있다.

 

1. Private variables and functions:

const makeCounter = () => {
  let count = 0;
  
  return () => {
    count++;
    console.log(count);
  }
}

let counter = makeCounter();
counter(); // logs 1
counter(); // logs 2
counter(); // logs 3

makeCounter가 호출되면, 새로운 count scope가 형성되고, 그 변수 값은 0이다.

그런 다음 이 스코프를 "closes over"하는 새 화살표 함수를 반환하고 호출될 때마다 카운트 변수를 증가시킨다.

counter()를 호출할 때마다 외부 함수의 범위에서 원래 count 변수를 "closing over" 하고있기 때문에 count 변수가 증가하고 새로운 value 값이 콘솔에 기록된다.
따라서 count 변수는 반환된 개체 외부에 노출되지 않으므로 makeCounter() 메서드를 통해서만 액세스하거나 수정할 수 있는 private 변수이다.

 

2. Partial function:

function add(x) {
  return function(y) {
    return x + y;
  }
}

let add5 = add(5);

console.log(add5);
// function(y) {
//   return x + y;
// }

console.log(add5(3)); // 8
console.log(add5(4)); // 9

이 예제에서 add() 함수는 하나의 argument를 사용하고 외부 함수의 스코프(범위)에서 해당 인수와 x 값의 합을 반환하는 다른 함수를 반환한다.

이를 통해 x 값을 전달하고 argument에 항상 해당 값을 추가하는 새 함수를 다시 가져와 add() 함수를 "부분적으로" 사용할 수 있다.

필요에 따라 다른 y 값을 전달하면서 다른 함수처럼 새 함수를 사용할 수 있다.

Comments