💻 Dev

처음부터 만드는 Compose — 함수를 역순으로 연결하기

# 처음부터 만드는 Compose
`Pipe`는 왼쪽에서 오른쪽으로 함수를 실행하지만, `Compose`는 오른쪽에서 왼쪽으로 실행됩니다. 수학 표기법처럼 함수를 작성할 수 있어 함수형 프로그래밍의 핵심 도구입니다.

기본 구현


```javascript
const compose = (...fns) => {
return (arg) => {
return fns.reduceRight((acc, fn) => fn(acc), arg);
};
};
```
`reduceRight`로 배열을 오른쪽부터 왼쪽으로 순회합니다.

사용 예제


```javascript
const add10 = x => x + 10;
const multiply2 = x => x * 2;
const subtract5 = x => x - 5;
// compose(add10, multiply2, subtract5)
// 실행 순서: subtract5 → multiply2 → add10
const compute = compose(add10, multiply2, subtract5);
console.log(compute(5)); // (5-5)*2+10 = 10
```

타입스크립트


```typescript
function compose(...fns: Array<(arg: any) => any>) {
return (arg: T) => fns.reduceRight((acc, fn) => fn(acc), arg);
}
```

Pipe vs Compose?


  • Pipe: 왼쪽→오른쪽, 읽기 쉬움 `pipe(f, g, h)(x)`

  • Compose: 오른쪽→왼쪽, 수학처럼 `compose(f, g, h)(x) = f∘g∘h`

  • 팀 선호도에 따라 선택하세요. Ramda, Lodash/fp는 둘 다 제공합니다.
    💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!