🛠️ 처음부터 만드는 Compose — 함수를 우에서 좌로 연결하기
Pipe는 좌에서 우로 함수를 연결한다면, Compose는 우에서 좌로 함수를 연결합니다. 수학의 함수 합성 `f(g(x))`처럼 동작하죠.
기본 구현
```typescript
function compose
return (value: T) =>
fns.reduceRight((acc, fn) => fn(acc), value);
}
// 사용 예
const addTwo = (x: number) => x + 2;
const multiplyByThree = (x: number) => x * 3;
const square = (x: number) => x * x;
const transform = compose(square, multiplyByThree, addTwo);
console.log(transform(5)); // ((5 + 2) * 3)^2 = 441
```
타입 안전 버전 (고급)
```typescript
function compose(
f: (b: B) => C,
g: (a: A) => B
): (a: A) => C {
return (a: A) => f(g(a));
}
const getAge = (user: {age: number}) => user.age;
const addYears = (age: number) => age + 10;
const composed = compose(addYears, getAge);
console.log(composed({age: 20})); // 30
```
Pipe vs Compose
Pipe가 더 선호되지만, Compose는 부분 적용과 조합할 때 강력합니다.
Comments (0)
💬
No comments yet.
Be the first to comment!