💻 Dev

🛠️ 처음부터 만드는 Compose — 함수들을 역순으로 연결하기

# 함수 합성(Compose)이란?
Pipe는 왼쪽에서 오른쪽으로 함수를 연결합니다. Compose는 반대예요. 오른쪽에서 왼쪽으로 실행됩니다.
```typescript
const compose = (...fns: Array<(arg: T) => T>) =>
(value: T) => fns.reduceRight((acc, fn) => fn(acc), value);
// 사용 예
const add5 = (x: number) => x + 5;
const multiply2 = (x: number) => x * 2;
const square = (x: number) => x * x;
const calculate = compose(square, multiply2, add5);
console.log(calculate(3)); // ((3 + 5) * 2)^2 = 256
```

Pipe vs Compose


Pipe: `value |> f1 |> f2 |> f3` (왼쪽 → 오른쪽)
Compose: `f3(f2(f1(value)))` (오른쪽 → 왼쪽)
실전에서는 읽기 순서가 자연스러운 Pipe를 더 많이 쓰지만, 함수형 프로그래밍 전통에서는 Compose를 선호합니다. 특히 고차 함수(Higher-Order Function) 조합에서 유용해요.

실전 예제


```typescript
const trim = (s: string) => s.trim();
const toLowerCase = (s: string) => s.toLowerCase();
const removeSpaces = (s: string) => s.replace(/\s+/g, '');
const normalize = compose(removeSpaces, toLowerCase, trim);
console.log(normalize(' HELLO WORLD ')); // 'helloworld'
```
핵심은 `reduceRight()`로 오른쪽부터 시작하는 것. Pipe는 `reduce()`, Compose는 `reduceRight()`라고 기억하면 됩니다!
참고: [lodash compose](https://lodash.com/docs#compose) | [Ramda compose](https://ramdajs.com/docs/#compose)
💬 0
👁 0 views

Comments (0)

💬

No comments yet.

Be the first to comment!