💻 Dev

🛠️ 처음부터 만드는 Tap — 파이프라인을 막지 않고 디버깅하기

함수형 프로그래밍에서 데이터를 변환하며 동시에 검증하거나 로깅하고 싶을 때가 있습니다. 이런 상황에서 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));
```

핵심 특징


  • ✅ 데이터 흐름을 방해하지 않음

  • ✅ Pipe/Compose와 자연스럽게 결합

  • ✅ 로깅, 검증, 메트릭 기록에 최적

  • ✅ 함수형 스타일 유지

  • 참고: [함수형 프로그래밍 패턴](https://mostly-adequate.gitbook.io/mostly-adequate-guide/)
    💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!