React Currying
- Currying(커링) 기법은 인자가 여러개인 함수의 일부 인자를 고정시키는 새로운 함수를 만드는 기법
- 인자가 n개인 함수를 n개로 분리하여 사용하게끔 만드는 기법
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function helloFunc(word, name) { | |
console.log(`${word}, ${name}`); | |
} |
└ word와 name이라는 두 개의 인자를 받아서 출력해주는 단순한 형태의 함수
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function helloFunc(word) { | |
return function (name) { | |
console.log(`${word}, ${name}`); | |
}; | |
} | |
const printHello = helloFunc("hello"); | |
printHello("Tibetan Fox"); // hello, Tibetan Fox | |
printHello("Tiger"); // hello, Tiger |
┌ 위의 함수에 커링을 적용함
├ n(2)개의 인자를 받던 함수가 n(2)개로 쪼개진 것을 볼 수 있음
├ 또한, 첫 번째로 받던 인자인 word를 hello라는 값으로 고정하고 name만 변경하면서 사용 가능한 것 또한 볼 수 있음
├ 즉, 커링 기법은 일부 인자에 같은 값을 반복적으로 사용할 때
└ 그 반복되는 인자를 고정함으로써 중복을 최소화 하기에 적합한 기법
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function helloFunc(word, name, word2, name2) { | |
console.log(`${word}, ${name} || ${word2}, ${name2}`); | |
} |
└ 위는 인자가 4개나 되는 함수
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function helloFunc(word) { | |
return function (name) { | |
return function(word2){ | |
return function(name2){ | |
console.log(`${word}, ${name} || ${word2}, ${name2}`) | |
} | |
} | |
}; | |
} |
┌ 위 함수에 커링을 적용함
└ 커링 기법 자체가 부분 부분 나눈 함수를 체인으로 생성하여 사용하게끔 하는 방식이므로 위와 같은 모습이 되어버림
주의할 점
- 커링 기법을 적용할 때는 인자의 순서가 매우 중요함
- 변동 가능성이 적은 인자는 앞에, 변동 가능성이 높은 인자는 뒤에 배치해야 함
- 반드시 이 점을 고려하면서 커링을 사용해야 함
'React > 2022-上' 카테고리의 다른 글
flatten, unflatten (0) | 2022.04.24 |
---|---|
Recursive Functions (0) | 2022.04.24 |
React HOC vs HOF (0) | 2022.04.18 |
JS Closure (0) | 2022.04.18 |
권한 분기 (0) | 2022.04.18 |