커링이란 다중 인자를 함수로 받는 일종의 함수 체인으로 변환하는 기법이다.
커링 함수는 함수를 변형시켜 한 번에 하나의 인자만을 받는 함수로 변환하고, 중첩된 함수들을 반환한다.
커링함수 사용법
//함수 선언식일 경우의 커링 함수
function curryingFunction(a){
return function innerCurryingFunction(b){
return a+b
}
}
//화살표 함수일 경우의 커링 함수
const curryingFunction = a => b => a + b
// 인자를 하나만 받을 수 있다.
console.log(curryingFunction(1)(2)) //3
그러나 이렇게 놓고 보았을 때는
function normalFunction(a,b){
return a + b
}
console.log(normalFunction(1,2))//3
일반함수와 달라보이지 않고 오히려 커링함수가 더 복잡하게 느껴질 수 있다.
커링된 함수는 인자를 하나만 받아들이기 때문에 인자가 하나씩 제공될 때마다 새로운 함수가 생성된다. 순차적으로 함수에 인자를 적용할 수 있다.
// 커링 함수
const add = a => b => a + b
const add_A = add(2)
console.log(add_A) // [Function (anonymous)]
//익명 함수가 리턴되는 것을 볼 수 있다.
console.log(add_A(4)) // 6
// 일반 함수의 경우
const add = (a,b) => a + b
const add_A = add(2)
console.log(add_A) // a=2, b=undefined이기 때문에 undefined가 리턴
//인자를 순차적으로 적용할 수 없다.
함수의 인자를 순차적으로 적용할 수 있다는 장점이 있다.
커링된 함수는 인자를 한번에 하나씩 받아들이기 때문에 각각의 인자에 따라 다양한 함수를 생성할 수 있다.
예를 들어 문자열을 조작하는 함수를 만든다는 예를 들 때,
function stringConversion(str) {
return {
upperCaseChange: function () {
return str.toUpperCase(); // 소문자를 대문자로 바꾸는 함수
},
lowerCaseChnage: function () {
return str.toLowerCase(); // 대문자를 소문자로 바꾸는 함수
},
replace: function(target, replacement) {
return str.replace(target, replacement); // 문자를 치환하는 함수
}
};
}
const a = stringConversion("a");
const b = stringConversion("B");
const c = stringConversion("c");
// a 와 b의 리턴 값 -> 익명 함수를 리턴한다.
//upperCaseChange: [Function: upperCaseChange],
//lowerCaseChnage: [Function: lowerCaseChnage],
//replace: [Function: replace]
console.log(a.upperCaseChange()); // "A"
console.log(b.lowerCaseChnage()); // "b"
console.log(c.replace("c","b")) // "b"
이런식으로 함수의 재사용성을 증가시킬 수 있고, 유연성을 더 할 수 있다.
보통 onClick 이벤트에서 인자를 전달할 경우 익명 함수를 이용하여 전달을 해야했다.
// 일반적인 경우
const eventHandler = (item) => {
console.log(item)
}
//...
<button onClick={eventHandler(item)}/> // X
<button onClick={()=>{eventHandler(item)}/> // O
//커링 함수를 적용한 경우
const eventHandler = (item) => (event) =>{
console.log(item)
}
<button onClick={eventHandler(item)}/>
이런식으로 좀 더 깔끔하게 이벤트 핸들러에 적용 할 수 있다.