💻 Dev

🛠️ 처음부터 만드는 Curry — 함수의 인자를 단계적으로 받기

Curry란?


여러 개의 인자를 받는 함수를 한 번에 하나씩 인자를 받는 함수들의 연쇄로 변환하는 기법입니다.
```javascript
// 변환 전
const add = (a, b, c) => a + b + c;
add(1, 2, 3); // 6
// 변환 후
const curriedAdd = curry(add);
const add1 = curriedAdd(1); // 함수 반환
const add1_2 = add1(2); // 함수 반환
const result = add1_2(3); // 6
// 또는 한 줄로
curriedAdd(1)(2)(3); // 6
```

직접 구현해보기


```javascript
function curry(fn) {
return function curried(...args) {
// 인자 개수가 충분하면 함수 실행
if (args.length >= fn.length) {
return fn(...args);
}
// 아니면 남은 인자를 받는 함수 반환
return (...nextArgs) => curried(...args, ...nextArgs);
};
}
```

실전 예제


```javascript
// HTTP 요청 빌더
const makeRequest = (method, url, data) =>
`${method} to ${url} with ${JSON.stringify(data)}`;
const curriedRequest = curry(makeRequest);
const post = curriedRequest('POST');
const postToAPI = post('https://api.example.com');
// 나중에 필요한 데이터만 전달
postToAPI({ name: 'John' });
// 'POST to https://api.example.com with {"name":"John"}'
// 또는 다양한 조합
const getUsers = curriedRequest('GET')('https://api.example.com/users');
```

왜 쓸까?


  • 함수 재사용: 부분 적용으로 새로운 함수 생성

  • 함수 조합: Pipe/Compose와 함께 우아한 코드

  • 설정 캡슐화: 설정은 먼저, 데이터는 나중에

  • ⚠️ 주의


    JavaScript의 동적 인자는 `fn.length`(정의된 인자 개수)로만 판단합니다. Rest 파라미터가 있으면 작동하지 않으므로 명시적으로 인자 개수를 전달하세요:
    ```javascript
    function curryN(n, fn) {
    return function curried(...args) {
    if (args.length >= n) return fn(...args);
    return (...nextArgs) => curried(...args, ...nextArgs);
    };
    }
    ```
    💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!