🛠️ 처음부터 만드는 Compose/Pipe — 함수들을 엮어서 데이터 흐름을 만들기
함수형 프로그래밍의 가장 우아한 패턴이 바로 함수 조합(Composition)입니다. 여러 함수를 연결해서 데이터를 한 흐름으로 처리하는 개념이죠.
Pipe: 왼쪽→오른쪽으로 실행 (직관적)
Compose: 오른쪽→왼쪽으로 실행 (수학적: f(g(x)))
```javascript
function pipe(...fns) {
return (value) => fns.reduce((acc, fn) => fn(acc), value);
}
const add = (n) => (x) => x + n;
const multiply = (n) => (x) => x * n;
const calculate = pipe(
add(5), // 입력 + 5
multiply(2), // 결과 * 2
add(10) // 결과 + 10
);
calculate(3); // 26
```
```javascript
const trim = (s) => s.trim();
const toLowerCase = (s) => s.toLowerCase();
const splitWords = (s) => s.split(' ');
const filterEmpty = (arr) => arr.filter(w => w);
const join = (sep) => (arr) => arr.join(sep);
const normalizeText = pipe(
trim,
toLowerCase,
splitWords,
filterEmpty,
join('-')
);
normalizeText(' Hello WORLD '); // "hello-world"
```
```javascript
function compose(...fns) {
return (value) => fns.reduceRight((acc, fn) => fn(acc), value);
}
// 반대 순서로 작성
const calculate = compose(
add(10),
multiply(2),
add(5)
);
```
핵심: reduce로 함수 배열을 단일 함수로 축약. 실무에서는 Lodash의 `_.flow()`나 Ramda 사용 권장.
Pipe vs Compose의 차이
Pipe: 왼쪽→오른쪽으로 실행 (직관적)
Compose: 오른쪽→왼쪽으로 실행 (수학적: f(g(x)))
Pipe 구현
```javascript
function pipe(...fns) {
return (value) => fns.reduce((acc, fn) => fn(acc), value);
}
const add = (n) => (x) => x + n;
const multiply = (n) => (x) => x * n;
const calculate = pipe(
add(5), // 입력 + 5
multiply(2), // 결과 * 2
add(10) // 결과 + 10
);
calculate(3); // 26
```
실전: 텍스트 정규화
```javascript
const trim = (s) => s.trim();
const toLowerCase = (s) => s.toLowerCase();
const splitWords = (s) => s.split(' ');
const filterEmpty = (arr) => arr.filter(w => w);
const join = (sep) => (arr) => arr.join(sep);
const normalizeText = pipe(
trim,
toLowerCase,
splitWords,
filterEmpty,
join('-')
);
normalizeText(' Hello WORLD '); // "hello-world"
```
Compose 구현
```javascript
function compose(...fns) {
return (value) => fns.reduceRight((acc, fn) => fn(acc), value);
}
// 반대 순서로 작성
const calculate = compose(
add(10),
multiply(2),
add(5)
);
```
핵심: reduce로 함수 배열을 단일 함수로 축약. 실무에서는 Lodash의 `_.flow()`나 Ramda 사용 권장.
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!