🛠️ 처음부터 만드는 Pipe — 함수를 좌에서 우로 연결하기
# 🛠️ 처음부터 만드는 Pipe — 함수를 좌에서 우로 연결하기
Pipe는 여러 함수를 순차적으로 연결하는 유틸리티입니다. Compose와 반대로 왼쪽에서 오른쪽으로 읽어요.
Compose는 `compose(f, g, h)(x) = f(g(h(x)))`로 우→좌 방향이라 읽기 어렵습니다. Pipe는 자연스러운 흐름대로 진행합니다.
```js
// Compose (우→좌) — 읽기 어려움
const result = compose(square, add2, multiply3)(5); // 5 * 3 + 2 제곱
// Pipe (좌→우) — 읽기 쉬움
const result = pipe(multiply3, add2, square)(5); // 5 * 3 + 2 제곱
```
```js
const pipe = (...fns) => (initialValue) =>
fns.reduce((acc, fn) => fn(acc), initialValue);
```
```js
const multiply = (x) => x * 3;
const add = (x) => x + 2;
const square = (x) => x * x;
const calculate = pipe(multiply, add, square);
console.log(calculate(5)); // (5*3 + 2)^2 = 289
```
```js
const pipeAsync = (...fns) => async (initialValue) => {
let result = initialValue;
for (const fn of fns) {
result = await Promise.resolve(fn(result));
}
return result;
};
const fetchUser = async (id) => ({ id, name: 'Alice' });
const getAge = async (user) => ({ ...user, age: 30 });
const getUserProfile = pipeAsync(fetchUser, getAge);
await getUserProfile(1); // { id: 1, name: 'Alice', age: 30 }
```
Compose와 반대: 좌→우 방향으로 읽음
데이터 변환 파이프라인: 함수형 프로그래밍의 핵심
가독성: 단계적 변환을 선형적으로 표현
더 알아보기: [함수형 프로그래밍 패턴 - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functional_Programming)
Pipe는 여러 함수를 순차적으로 연결하는 유틸리티입니다. Compose와 반대로 왼쪽에서 오른쪽으로 읽어요.
왜 필요할까?
Compose는 `compose(f, g, h)(x) = f(g(h(x)))`로 우→좌 방향이라 읽기 어렵습니다. Pipe는 자연스러운 흐름대로 진행합니다.
```js
// Compose (우→좌) — 읽기 어려움
const result = compose(square, add2, multiply3)(5); // 5 * 3 + 2 제곱
// Pipe (좌→우) — 읽기 쉬움
const result = pipe(multiply3, add2, square)(5); // 5 * 3 + 2 제곱
```
기본 구현
```js
const pipe = (...fns) => (initialValue) =>
fns.reduce((acc, fn) => fn(acc), initialValue);
```
실제 사용
```js
const multiply = (x) => x * 3;
const add = (x) => x + 2;
const square = (x) => x * x;
const calculate = pipe(multiply, add, square);
console.log(calculate(5)); // (5*3 + 2)^2 = 289
```
심화: 비동기 함수 지원
```js
const pipeAsync = (...fns) => async (initialValue) => {
let result = initialValue;
for (const fn of fns) {
result = await Promise.resolve(fn(result));
}
return result;
};
const fetchUser = async (id) => ({ id, name: 'Alice' });
const getAge = async (user) => ({ ...user, age: 30 });
const getUserProfile = pipeAsync(fetchUser, getAge);
await getUserProfile(1); // { id: 1, name: 'Alice', age: 30 }
```
핵심
더 알아보기: [함수형 프로그래밍 패턴 - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functional_Programming)
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!