Skip to the solution
MediumFrontend6 min read

Implement compose() and pipe() for function composition

1k views

The problem

Problem, as an interviewer would state it: "Implement compose(...fns) and pipe(...fns) — both combine multiple single-argument functions into one, differing only in the ORDER they apply."

Examples:

Code
compose(square, double, addOne)(3); // square(double(addOne(3))) -- right to left
pipe(addOne, double, square)(3);    // square(double(addOne(3))) -- left to right, SAME result

Clarifying questions expected:

  • Which direction does "compose" apply by real, standard convention — right-to-left, or left-to-right?
  • Do the combined functions need to support multiple arguments, or just a single value threaded through?
  • What should an empty fns list (compose()) return?

Code / implementation expected: Yes — real, direct proof that compose and pipe produce the identical result for the same functions with reversed call order.

  • compose
  • pipe
  • functional

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: compose() and pipe() produce the identical result for the same functions, with only their argument order reversed

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 93 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Flatten and Unflatten a Nested Object (dot notation & arrays)

Continue