💻 Dev

🛠️ 처음부터 만드는 Compose — 함수를 우에서 좌로 연결하기

# Compose: 함수형 파이프라인의 필수 패턴
Pipe는 좌에서 우로 함수를 연결한다면, Compose는 우에서 좌로 함수를 연결합니다. 수학의 함수 합성 `f(g(x))`처럼 동작하죠.

기본 구현


```typescript
function compose(...fns: Array<(arg: T) => T>) {
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: 우→좌 실행 (수학적 정의에 맞음)

  • Pipe가 더 선호되지만, Compose는 부분 적용과 조합할 때 강력합니다.

    참고


  • [Lodash compose](https://lodash.com/docs#compose)

  • [함수 합성 개념](https://en.wikipedia.org/wiki/Function_composition)
  • 💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!