🛠️ 처음부터 만드는 Tap — 파이프라인을 막지 않고 디버깅하기
Tap의 역할
Tap은 값을 그대로 통과시키면서 부작용(side effect)을 수행합니다.
```javascript
const tap = (fn) => (value) => {
fn(value);
return value;
};
```
실전 예제
파이프라인에서 디버깅:
```javascript
const pipe = (...fns) => (value) =>
fns.reduce((acc, fn) => fn(acc), value);
const log = (label) => tap((val) => console.log(label, val));
pipe(
(x) => x * 2,
log('Step 1'),
(x) => x + 10,
log('Step 2'),
(x) => x / 3
)(5);
// Step 1 10
// Step 2 20
// 결과: 6.666...
```
검증 또는 메트릭 기록:
```javascript
const logMetrics = tap((user) => {
metrics.increment('user.created');
if (!user.email) console.warn('Missing email');
});
const users = [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob' }
].map(logMetrics);
```
비동기 버전:
```javascript
const tapAsync = (fn) => async (value) => {
await fn(value);
return value;
};
await fetch('/api/data')
.then(res => res.json())
.then(tapAsync(data => saveToCache(data)))
.then(data => renderUI(data));
```
핵심 특징
참고: [함수형 프로그래밍 패턴](https://mostly-adequate.gitbook.io/mostly-adequate-guide/)
Comments (0)
💬
No comments yet.
Be the first to comment!