💻 Dev

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

Compose는 여러 함수를 우에서 좌로(오른쪽에서 왼쪽으로) 연결하는 함수입니다. Pipe의 반대 방향이죠.

왜 필요할까?


```javascript
// 함수들
const double = x => x * 2;
const addTen = x => x + 10;
const square = x => x * x;
// Compose 없이: 안쪽부터 바깥쪽으로 읽어야 함
const result = square(addTen(double(5)));
// 5 → 10 → 20 → 400
```
Compose를 쓰면 함수 실행 순서를 명확하게 정의할 수 있습니다.

구현하기


```javascript
const compose = (...fns) => x =>
fns.reduceRight((acc, fn) => fn(acc), x);
// 사용
const composed = compose(square, addTen, double);
console.log(composed(5)); // 400
```
reduceRight 사용이 핵심입니다. 배열을 오른쪽부터 왼쪽으로 순회하면서 함수를 적용합니다.

실무 예제


```javascript
const trim = str => str.trim();
const lowercase = str => str.toLowerCase();
const removeSpaces = str => str.replace(/\s+/g, '');
const normalize = compose(removeSpaces, lowercase, trim);
console.log(normalize(' HELLO WORLD '));
// 'helloworld'
```

Pipe vs Compose


  • Pipe: 좌에서 우로 (자연스러운 흐름) → `pipe(double, addTen, square)`

  • Compose: 우에서 좌로 (수학적 관례) → `compose(square, addTen, double)`

  • 실무에서는 Pipe가 더 직관적이지만, 함수형 프로그래밍 라이브러리들은 Compose를 자주 사용합니다.
    참고: Lodash의 `_.compose`, Ramda의 `R.compose` 참조
    💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!