🛠️ 처음부터 만드는 Pipe — 함수를 연결해 데이터 파이프라인 만들기
함수를 레고 블록처럼 조립하면 어떨까요? `pipe`는 여러 함수를 순서대로 연결해, 앞 함수의 출력을 다음 함수의 입력으로 자동 전달합니다.
`pipe(f, g, h)(x)`는 `h(g(f(x)))`와 같습니다. 왼쪽에서 오른쪽으로 데이터가 흐릅니다.
```typescript
type Fn = (arg: any) => any;
function pipe(...fns: Fn[]) {
return (input: T) => fns.reduce((acc, fn) => fn(acc), input as any);
}
```
단 3줄입니다. `reduce`로 함수 배열을 순회하며, 이전 결과를 다음 함수에 넘깁니다.
```typescript
const process = pipe(
(s: string) => s.trim(),
(s: string) => s.toLowerCase(),
(s: string) => s.replace(/\s+/g, '-'),
);
process(' Hello World '); // 'hello-world'
```
API 호출처럼 비동기 함수도 연결할 수 있습니다.
```typescript
function asyncPipe(...fns: Fn[]) {
return (input: T) =>
fns.reduce(
(acc, fn) => Promise.resolve(acc).then(fn),
input as any,
) as Promise;
}
const fetchUser = asyncPipe(
(id: number) => fetch(`/api/users/${id}`),
(res: Response) => res.json(),
(user: any) => user.name,
);
await fetchUser(1); // 'Alice'
```
가독성: 중첩 호출 `c(b(a(x)))` 대신 왼→오 흐름으로 읽힙니다
재사용: 작은 함수를 조합해 새로운 함수를 만듭니다
테스트: 각 단계를 독립적으로 테스트할 수 있습니다
> TC39 [Pipeline Operator 제안](https://github.com/tc39/proposal-pipeline-operator)이 Stage 2에 있어, 미래에는 `x |> f |> g` 문법이 가능해질 수 있습니다.
핵심 원리
`pipe(f, g, h)(x)`는 `h(g(f(x)))`와 같습니다. 왼쪽에서 오른쪽으로 데이터가 흐릅니다.
구현
```typescript
type Fn = (arg: any) => any;
function pipe
return (input: T) => fns.reduce((acc, fn) => fn(acc), input as any);
}
```
단 3줄입니다. `reduce`로 함수 배열을 순회하며, 이전 결과를 다음 함수에 넘깁니다.
사용 예제
```typescript
const process = pipe
(s: string) => s.trim(),
(s: string) => s.toLowerCase(),
(s: string) => s.replace(/\s+/g, '-'),
);
process(' Hello World '); // 'hello-world'
```
비동기 버전
API 호출처럼 비동기 함수도 연결할 수 있습니다.
```typescript
function asyncPipe
return (input: T) =>
fns.reduce(
(acc, fn) => Promise.resolve(acc).then(fn),
input as any,
) as Promise
}
const fetchUser = asyncPipe
(id: number) => fetch(`/api/users/${id}`),
(res: Response) => res.json(),
(user: any) => user.name,
);
await fetchUser(1); // 'Alice'
```
왜 유용한가?
> TC39 [Pipeline Operator 제안](https://github.com/tc39/proposal-pipeline-operator)이 Stage 2에 있어, 미래에는 `x |> f |> g` 문법이 가능해질 수 있습니다.
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!