AniUI Academy

Peek at a value mid-pipeline

easyFunctions & Closures+150 XPPractice

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 going

Slip 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 visible

What it has to do

  • Return the original value, ignoring whatever fn returns.
  • Call fn exactly once with the value as its only argument.
  • Return the identical reference, not a copy.
  • Let fn mutate an object value in place.

Notes

  • The classic bug is return fn(value) — that returns whatever fn gave you, which is usually undefined.
  • tap is 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.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.