🛠️ 처음부터 만드는 Compose — 함수를 우에서 좌로 연결하기
# Compose: 함수 합성의 핵심
Compose는 Pipe의 반대 개념입니다. 여러 함수를 우에서 좌로 연결하여 함수형 프로그래밍의 우아함을 극대화합니다.
```javascript
const compose = (...fns) => (value) =>
fns.reduceRight((acc, fn) => fn(acc), value);
// 사용 예
const add5 = x => x + 5;
const multiply2 = x => x * 2;
const subtract3 = x => x - 3;
// 우에서 좌로: subtract3 → multiply2 → add5
const calculate = compose(add5, multiply2, subtract3);
console.log(calculate(10));
// (10 - 3) * 2 + 5 = 19
```
```javascript
const composeAsync = (...fns) => async (value) => {
let result = value;
for (const fn of fns.reverse()) {
result = await Promise.resolve(fn(result));
}
return result;
};
const fetchUser = id => Promise.resolve({id, name: 'John'});
const extractName = user => user.name;
const toUpperCase = str => str.toUpperCase();
const getUserName = composeAsync(toUpperCase, extractName, fetchUser);
await getUserName(1); // 'JOHN'
```
Pipe vs Compose: Pipe는 좌→우(가독성), Compose는 우→좌(수학적)
함수 순서: 실행 순서와 선언 순서가 반대 — reduceRight 사용
타입 안정성: TypeScript에서는 제너릭으로 입출력 타입 명시
[JavaScript.info - Function composition](https://javascript.info/currying-partials)
Compose는 Pipe의 반대 개념입니다. 여러 함수를 우에서 좌로 연결하여 함수형 프로그래밍의 우아함을 극대화합니다.
기본 개념
```javascript
const compose = (...fns) => (value) =>
fns.reduceRight((acc, fn) => fn(acc), value);
// 사용 예
const add5 = x => x + 5;
const multiply2 = x => x * 2;
const subtract3 = x => x - 3;
// 우에서 좌로: subtract3 → multiply2 → add5
const calculate = compose(add5, multiply2, subtract3);
console.log(calculate(10));
// (10 - 3) * 2 + 5 = 19
```
고급: 비동기 처리
```javascript
const composeAsync = (...fns) => async (value) => {
let result = value;
for (const fn of fns.reverse()) {
result = await Promise.resolve(fn(result));
}
return result;
};
const fetchUser = id => Promise.resolve({id, name: 'John'});
const extractName = user => user.name;
const toUpperCase = str => str.toUpperCase();
const getUserName = composeAsync(toUpperCase, extractName, fetchUser);
await getUserName(1); // 'JOHN'
```
실전 팁
[JavaScript.info - Function composition](https://javascript.info/currying-partials)
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!