🛠️ 처음부터 만드는 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'
```
실전 팁
[JavaScript.info - Function composition](https://javascript.info/currying-partials)
Comments (0)
💬
No comments yet.
Be the first to comment!