Functional-Light JavaScript, v3

Piping & Composition Solution

Kyle Simpson

Kyle Simpson

You Don't Know JS
Functional-Light JavaScript, v3

Check out a free preview of the full Functional-Light JavaScript, v3 course

The "Piping & Composition Solution" Lesson is part of the full, Functional-Light JavaScript, v3 course featured in this preview video. Here's what you'd learn in this lesson:

Kyle live codes the solution to the exercise.

Preview
Close

Transcript from the "Piping & Composition Solution" Lesson

[00:00:00]
>> Kyle Simpson: Okay, let's talk about the exercise on composition. We could either implement compose and then pipe in terms of compose or reverse. I'm actually gonna do the reverse and the reason is purely for simplicity. Because pipe goes left to right, I can use a very convenient for loop for that.

[00:00:20]
But there are lots of ways to implement either compose or pipe, you could have used reduce or reduce right or other utilities like that. I'm just gonna use a simple for loop. So, pipe is going to take in a list of functions. And I'm gonna gather those up into an array called fns, which stands for functions and it needs to return back a new function.

[00:00:44]
That was piped, and that is going to receive a single input value that it passes along to the first one. Now, my strategy here is to be able to handle any number of functions, essentially I want to call the first function and then whatever it returns, save that.

[00:01:03]
And if there's another function, that becomes the input and then save that output. And then just keep doing that until there's no more functions, and then I have my output. So I'm just gonna set up a simple for loop, let fn of fns, and I'm going to say, v = fn, passing in v.

[00:01:26]
So in other words, take the current input, whatever it is. Pass it into the current function, and capture that output. And then iterate the loop again. If there's another function, do that again, and again, and again. And at the very end, return v.
>> Kyle Simpson: That should handle any number of functions.

[00:01:46]
To implement the compose function, I gather all of the functions into an array called fns. And I need to pass fns to pipe but I need to reverse the order. So I'm gonna say return pipe, I'm gonna pass in fns that has been reversed. I'll spread fns that has been reversed.

[00:02:10]
Yes?
>> Speaker 2: What if we started with compose instead of pipe?
>> Kyle Simpson: You can start with compose, it's just a little less clean because your for of loop, if you choose to use a loop, needs to loop over the reverse of the arrays rather than the array itself. All right, let's test this just to make sure.

[00:02:36]
>> Kyle Simpson: And we get all trues.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now