💻 Dev

🛠️ 처음부터 만드는 Curry — 함수를 부분 적용 가능하게 만들기

Curry란?


Curry는 여러 개의 인자를 받는 함수를 단일 인자를 받는 함수의 연쇄로 변환하는 기법입니다.
```javascript
// 일반 함수
const add = (a, b, c) => a + b + c;
add(1, 2, 3); // 6
// Curry 함수
const curriedAdd = curry(add);
const add1 = curriedAdd(1); // 부분 적용
const add1_2 = add1(2); // 부분 적용
const result = add1_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);
};
}
```

TypeScript 버전


```typescript
function curry any>(fn: T): (...args: any[]) => any {
const arity = fn.length;

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

실전 예제


```javascript
const multiply = (a, b, c) => a * b * c;
const curriedMultiply = curry(multiply);
const multiplyBy2 = curriedMultiply(2);
const multiplyBy2_3 = multiplyBy2(3);
console.log(multiplyBy2_3(4)); // 24
// API 요청 로직
const makeRequest = (method, url, data) => `${method} ${url} ${JSON.stringify(data)}`;
const curriedRequest = curry(makeRequest);
const postToAPI = curriedRequest('POST');
const postToUsers = postToAPI('/api/users');
console.log(postToUsers({ name: 'John' }));
// POST /api/users {"name":"John"}
```

핵심 포인트


장점: 함수 조합(composition)과 부분 적용(partial application) 가능
사용처: API 래퍼, 이벤트 핸들러, 데이터 변환 파이프라인
⚠️ 주의: `fn.length`는 기본값/Rest 파라미터가 있으면 정확하지 않음
레퍼런스: [MDN - Partial application](https://developer.mozilla.org/en-US/docs/Glossary/Partial_application)
💬 0
👁 0 views

Comments (0)

💬

No comments yet.

Be the first to comment!