💻 Dev

🛠️ 처음부터 만드는 Compose — 함수들을 오른쪽에서 왼쪽으로 연결하기

# 🛠️ 처음부터 만드는 Compose

Compose가 뭐죠?


Compose는 Pipe와 정반대입니다. 여러 함수를 조합해서 하나의 함수로 만드는데, 오른쪽에서 왼쪽으로 실행됩니다.
```javascript
const compose = (...fns) => (value) =>
fns.reduceRight((acc, fn) => fn(acc), value);
const add = (x) => x + 10;
const multiply = (x) => x * 2;
const square = (x) => x ** 2;
const combined = compose(square, multiply, add);
combined(5); // (5 + 10) * 2² = 900
```

왜 Pipe 대신 Compose?


수학적 함수 합성 표기법과 일치합니다: `f(g(h(x)))` = `compose(f, g, h)(x)`

실무 예시


```javascript
const getUser = (id) => ({ id, name: 'John' });
const getName = (user) => user.name.toUpperCase();
const getUserNameUpperCase = compose(getName, getUser);
getUserNameUpperCase(1); // 'JOHN'
```

비동기 Compose


```javascript
const composeAsync = (...fns) => async (value) => {
let result = value;
for (let i = fns.length - 1; i >= 0; i--) {
result = await fns[i](result);
}
return result;
};
const fetchUser = async (id) => ({ name: 'John' });
const toUpper = async (user) => user.name.toUpperCase();
const pipeline = composeAsync(toUpper, fetchUser);
await pipeline(1); // 'JOHN'
```

주의사항


  • 오른쪽부터 실행됨을 기억하세요 (수학 표기법)

  • TypeScript에서는 함수 시그니처를 명확히 하세요

  • 참고: [Ramda compose](https://ramdajs.com/docs/#compose), [Lodash compose](https://lodash.com/docs/#compose)
    💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!