🛠️ 처음부터 만드는 Pipe — 함수를 연결해 데이터 파이프라인 만들기
핵심 원리
`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` 문법이 가능해질 수 있습니다.
Comments (0)
💬
No comments yet.
Be the first to comment!