🛠️ 처음부터 만드는 Pipe — 함수들을 순서대로 연결하기
# Pipe란?
여러 함수를 왼쪽부터 오른쪽으로 순차 실행하는 유틸리티입니다. 이전 함수의 결과가 다음 함수의 입력이 됩니다.
```javascript
const pipe = (...fns) => (value) => fns.reduce((acc, fn) => fn(acc), value);
// 사용
const addOne = (x) => x + 1;
const double = (x) => x * 2;
const toString = (x) => `Result: ${x}`;
const transform = pipe(addOne, double, toString);
console.log(transform(5)); // "Result: 12"
```
# 타입스크립트 버전
더 안전한 타입 지원:
```typescript
type Fn = (arg: T) => R;
const pipe =(...fns: Array>) =>
(value: T) => fns.reduce((acc, fn) => fn(acc), value);
// 타입 추론됨
const process = pipe(
(x: number) => x + 1,
(x: number) => x * 2,
(x: number) => `${x}`
);
```
# 실무 예제
API 응답 처리:
```javascript
const fetchUser = pipe(
async (id) => await fetch(`/api/user/${id}`),
(res) => res.json(),
(data) => ({ ...data, fetched: new Date() }),
(user) => console.log('Processed:', user)
);
```
# Compose vs Pipe
Compose: 오른쪽→왼쪽 (수학 함수 합성 방식)
Pipe: 왼쪽→오른쪽 (읽기 직관적)
Pipe가 실무에서 더 자주 사용됩니다!
📖 관련: [Lodash flow](https://lodash.com/docs/4.17.21#flow)
여러 함수를 왼쪽부터 오른쪽으로 순차 실행하는 유틸리티입니다. 이전 함수의 결과가 다음 함수의 입력이 됩니다.
```javascript
const pipe = (...fns) => (value) => fns.reduce((acc, fn) => fn(acc), value);
// 사용
const addOne = (x) => x + 1;
const double = (x) => x * 2;
const toString = (x) => `Result: ${x}`;
const transform = pipe(addOne, double, toString);
console.log(transform(5)); // "Result: 12"
```
# 타입스크립트 버전
더 안전한 타입 지원:
```typescript
type Fn
const pipe =
(value: T) => fns.reduce((acc, fn) => fn(acc), value);
// 타입 추론됨
const process = pipe(
(x: number) => x + 1,
(x: number) => x * 2,
(x: number) => `${x}`
);
```
# 실무 예제
API 응답 처리:
```javascript
const fetchUser = pipe(
async (id) => await fetch(`/api/user/${id}`),
(res) => res.json(),
(data) => ({ ...data, fetched: new Date() }),
(user) => console.log('Processed:', user)
);
```
# Compose vs Pipe
Pipe가 실무에서 더 자주 사용됩니다!
📖 관련: [Lodash flow](https://lodash.com/docs/4.17.21#flow)
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!