💻 Dev

🛠️ 처음부터 만드는 Curry — 함수의 인자를 부분 적용하기

Curry는 여러 인자를 받는 함수를 1개 인자씩 받는 함수들의 체인으로 변환하는 패턴입니다.

언제 쓸까?


```javascript
const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);
// 부분 적용으로 새 함수 만들기
const addOne = curriedAdd(1); // (b, c) => 1 + b + c
const addOneAndTwo = addOne(2); // (c) => 1 + 2 + c
const result = addOneAndTwo(3); // 6
// 또는 한 번에
curriedAdd(1)(2)(3); // 6
```

구현


```javascript
function curry(fn) {
const arity = fn.length; // 함수가 요구하는 인자 개수

return function curried(...args) {
if (args.length >= arity) {
return fn(...args);
}
return (...nextArgs) => curried(...args, ...nextArgs);
};
}
```

실제 예제


```javascript
const multiply = (a, b, c) => a * b * c;
const curriedMultiply = curry(multiply);
const double = curriedMultiply(2);
const result = double(3)(4); // 24
// 실무: 데이터 변환 파이프라인
const filter = curry((predicate, arr) => arr.filter(predicate));
const map = curry((fn, arr) => arr.map(fn));
const isEven = n => n % 2 === 0;
const filterEven = filter(isEven);
const mapDouble = map(n => n * 2);
const numbers = [1, 2, 3, 4, 5];
const result = mapDouble(filterEven(numbers)); // [4, 8]
```
: `fn.length`는 기본값 없는 인자 개수만 세므로, Rest parameter가 있으면 주의하세요. Curry는 Pipe, Compose와 함께 사용할 때 함수 합성의 진가를 발휘합니다!
💬 0
👁 0 views

Comments (0)

💬

No comments yet.

Be the first to comment!