🛠️ 처음부터 만드는 Compose — 함수를 우에서 좌로 연결하기
Pipe와 반대 방향으로 함수를 연결하는 유틸리티입니다. 수학적 함수 합성처럼 `f(g(x))` 형태로 동작하며, 우에서 좌로 실행됩니다.
```javascript
const compose = (...fns) => (x) => fns.reduceRight((acc, fn) => fn(acc), x);
const add5 = (x) => x + 5;
const multiply2 = (x) => x * 2;
const composed = compose(add5, multiply2);
composed(3); // multiply2(3) = 6, then add5(6) = 11
```
```javascript
// 함수형 데이터 처리
const filterActive = (items) => items.filter(i => i.active);
const sortByDate = (items) => items.sort((a, b) => b.date - a.date);
const pipeline = compose(sortByDate, filterActive);
const result = fetchData().then(pipeline);
// 문자열 처리
const formatter = compose(
(str) => `PREFIX_${str}`,
(str) => str.toUpperCase(),
(str) => str.trim()
);
formatter(' hello '); // "PREFIX_HELLO"
```
Pipe (좌→우): 명령형 흐름처럼 순서대로 읽힘
Compose (우→좌): 수학적 함수 합성으로 표현
선호도에 따라 선택하세요. 함수형 프로그래밍에서는 Compose가 전통적이지만, 가독성을 위해서는 Pipe가 더 직관적일 수 있습니다.
참고: [Ramda Compose](https://ramdajs.com/docs/#compose) | [Lodash Flow](https://lodash.com/docs/#flow)
동작 원리
```javascript
const compose = (...fns) => (x) => fns.reduceRight((acc, fn) => fn(acc), x);
const add5 = (x) => x + 5;
const multiply2 = (x) => x * 2;
const composed = compose(add5, multiply2);
composed(3); // multiply2(3) = 6, then add5(6) = 11
```
실제 활용
```javascript
// 함수형 데이터 처리
const filterActive = (items) => items.filter(i => i.active);
const sortByDate = (items) => items.sort((a, b) => b.date - a.date);
const pipeline = compose(sortByDate, filterActive);
const result = fetchData().then(pipeline);
// 문자열 처리
const formatter = compose(
(str) => `PREFIX_${str}`,
(str) => str.toUpperCase(),
(str) => str.trim()
);
formatter(' hello '); // "PREFIX_HELLO"
```
Pipe와의 차이
Pipe (좌→우): 명령형 흐름처럼 순서대로 읽힘
Compose (우→좌): 수학적 함수 합성으로 표현
선호도에 따라 선택하세요. 함수형 프로그래밍에서는 Compose가 전통적이지만, 가독성을 위해서는 Pipe가 더 직관적일 수 있습니다.
참고: [Ramda Compose](https://ramdajs.com/docs/#compose) | [Lodash Flow](https://lodash.com/docs/#flow)
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!