AniUI Academy

Pipe functions left to right

mediumFunctions & Closures+250 XPPractice

pipe(f, g)(x) means g(f(x)). Same machinery as compose, opposite direction, and far easier to read for a data transformation: trim, then split, then count.

Implement pipe(...fns). It returns a function that invokes the leftmost function with all of the arguments it received, then passes each result to the next function to the right, and returns the rightmost function's result. Given no functions at all, the returned function returns its first argument unchanged.

Arguments

...fnsFunction[]
Any number of unary functions. The leftmost one may take any number of arguments.

Returns

Function — A function that applies fns left to right, threading the output of each into the next.

Examples

const trim = (s) => s.trim();
const split = (s) => s.split(" ");
const count = (parts) => parts.length;

const wordCount = pipe(trim, split, count);
wordCount("  hello world  "); // 2

The reading order matches the data flow — trim, then split, then count.

pipe((a, b) => a + b, (n) => n * 10)(2, 3); // 50

What it has to do

  • Apply the functions left to right.
  • Pass every argument to the leftmost function; the rest each receive one value.
  • With no functions, return the first argument unchanged.
  • Support a chain of more than two functions whose types change along the way.

Notes

  • pipe(f, g)(x) === g(f(x)). Same machinery as compose, opposite direction — pick whichever reads better at the call site.
  • This is the shape of RxJS's pipe and of the stage-2 pipeline operator proposal (x |> f |> g). Learn it once, apply it everywhere.
Asked atMetaShopifyStripe

Stuck? The javascript course covers everything this challenge needs.

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

Discussion

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

No comments yet. Be the first to say something.