Peek at a value mid-pipeline
Halfway through a map/filter/reduce chain something is wrong and you want to see the value. Pulling the chain apart into temporary variables to add a console.log is a hassle, so you slip in a function that runs a side effect and hands the value straight back.
Implement tap(value, fn). Call fn with value, then return value itself — the exact same reference, not a copy, and whatever fn returned is discarded. Because the value is passed by reference, fn is free to mutate an object it receives and those mutations are visible on the returned value.
Arguments
valueany- The value to inspect and then hand back untouched.
fnFunction- A side-effecting callback invoked with
value. Its return value is discarded.
Returns
any — The original value, byref — not a copy, and not whatever fn returned.
Examples
const result = [1, 2, 3]
.map((n) => n * 2)
.map((n) => tap(n, (v) => console.log(v)))
.filter((n) => n > 2);
// logs 2, 4, 6 — the chain keeps goingSlip a tap into any pipeline to peek at the value without breaking the chain.
const user = tap({ id: 1 }, (u) => { u.seen = true; });
user.seen; // true — mutations through the callback are visibleWhat it has to do
- Return the original value, ignoring whatever
fnreturns. - Call
fnexactly once with the value as its only argument. - Return the identical reference, not a copy.
- Let
fnmutate an object value in place.
Notes
- The classic bug is
return fn(value)— that returns whateverfngave you, which is usuallyundefined. tapis a debugging convenience; using it as a mutation point in "functional" code is a code smell. Keep side effects explicit.
Stuck? The javascript course covers everything this challenge needs.
- 1.returns the value, not the callback's result
- 2.calls the callback with the value
- 3.returns the same reference
- 4.keeps a chain of transformations intact
- 5.lets the callback mutate the value
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.