🛠️ 처음부터 만드는 Compose — 함수를 역순으로 연결하기
Compose란?
Compose는 여러 함수를 조합해 새로운 함수를 만드는 함수형 프로그래밍의 핵심 도구입니다. `Pipe`와 달리 오른쪽에서 왼쪽으로 함수를 실행합니다.
```javascript
const compose = (...fns) => (value) =>
fns.reduceRight((acc, fn) => fn(acc), value);
// 사용 예
const double = (n) => n * 2;
const addOne = (n) => n + 1;
const doubleThenAdd = compose(addOne, double);
console.log(doubleThenAdd(5)); // (5 * 2) + 1 = 11
```
작동 원리
`reduceRight`는 배열을 오른쪽에서 왼쪽으로 순회합니다. 따라서 함수들이 마지막부터 첫 번째 순서로 실행됩니다.
```javascript
const add = (n) => n + 10;
const multiply = (n) => n * 2;
const square = (n) => n ** 2;
// compose(a, b, c)(x) = a(b(c(x)))
const compute = compose(add, multiply, square);
console.log(compute(3));
// square(3) = 9
// multiply(9) = 18
// add(18) = 28
```
타입스크립트 버전
```typescript
type Fn = (x: any) => any;
const compose = (...fns: Fn[]) =>
(value: any) => fns.reduceRight((acc, fn) => fn(acc), value);
```
Pipe와의 차이
어느 것을 쓸지는 가독성과 팀 컨벤션에 따라 결정하세요.
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!