컴퓨터/JavaScript_typescript

[ JavaScript ] Currying 함수

수제녹차 2020. 9. 15. 16:55
728x90
반응형

* Curring 함수

여러 개의 인자를 받는 함수를 하나의 인자만 받는 함수로 나눠서 순차적으로 호출될 수 있게 체인 형태로 구성한 것

- 한 번에 하나의 인자만 전달

- 중간 과정상의 함수를 실행한 결과는 그다음 인자를 받기 위해 대기할 뿐, 마지막 인자가 전달되기 전까지는 원본 함수가 실행되지 않는다

- 마지막 호출로 실행 컨텍스트가 종료된 후에야 비로소 한꺼번에 GC의 수거대상이 된다.

evaluating function with multiple arguments, into a sequence of functions with a single argument

when a function, instead of taking all arguments at one time, takes the first one and return a new function that takes the second one and returns a new function which takes the third one, and so forth until all arguments have been fulfilled.

 

* 언제 유용하나?!

- 지연 실행 ( lazy execution ) : 당장 필요한 정보만 받아서 전달하고 또 필요한 정보가 들어오면 전달하는 식, 결국 마지막 인자가 넘어갈 때까지 함수 실행을 미룬다.

- 프로젝트 내에서 자주 쓰이는 함수의 매개변수가 항상 비슷하고 일부만 바뀌는 경우

바뀌는 일부만 인자로 받을 수 있도록!

 

  • Currying helps you to avoid passing the same variable again and again.
  • It helps to create a higher-order function. It is extremely helpful in event handling.
  • Little pieces can be configured and reused with ease.

 

 

* 커링 예제 코드

ex 1 )

var curry3 = function (func) {
    return function(a) {
        return function (b) {
            return func(a,b);
        }
    }
};

var getMaxWith10 = curry3(Math.max)(10);
console.log(getMaxWith10(8)); // 10
console.log(getMaxWith10(25)); // 25

ex 2 )

var curry5 = func => a => b => c =>  d => e => func(a,b,c,d,e);

- add3Curried(1)(2)(3)은 함수가 반환된 이후에도 arguments를 기억하고 있다

그리고 마지막에 a+b+c라는 body block이 실행된다

=> closure

- lodash : 함수형 util 제공

- addVAT 함수를 currying 함수로 만들어서

세금을 5% 매기는 함수, 세금을 2% 매기는 함수를 만들 수 있다.

 

source : 프로그래머스 react 스터디

정재남, 코어자바스크립트, 위키북스

반응형