Photo by Van Tay Media on Unsplash
Guess we have three functions, where one's result is being passed as second's input and so on. In this scenario how you will call all those functions? ( Share your thoughts on possible ways by commenting here 🤗 )
Before going further, I would like to welcome you to a new episode of series call Javascript Useful Snippets. In this series, I'm sharing some shortcodes and useful functions that can let you make your code faster and neat. So, if you haven't read my previous episodes' articles please check it out here or else stay tuned till the end to learn something new 😋 .
To call all functions in series or one by one, I've defined one simple function called pipe() which will take all functions as arguments in the same order of execution. And in return, it'll trigger left-to-right all functions in series by passing left one's result value to the right one's argument. Let me make it easy for you to explaining the snippet itself.
How pipe() function works ?
const pipe = (...fns) => fns.reduce((fn, g) => (...args) => g(fn(...args)));
As first, i've stored all functions arguments into array called fns by using spreading operator ( it's an concept of ES6 if you new to this word please check this first to learn in detail ) and in return i've called reduce method of array to execute every functions one by one and pass results one to another. And for same i've used again spreading operator to clone all results and passed it to current function. Let's use to know more it.
How to use pipe() function ?
const add = (x, y) => x + y
const square = (x) => x * x
const display = (x) => console.log(x)
const addNSquare = pipe(add, square, display);
addNSquare(6,5) // 121 in console
Here, I've first defined three functions to add a number, to square number, and just display number into the console. where I needed to pass add the result as a square argument and square result to display argument. So next, I've defined a new function using pipe function and passed all three functions as an argument in the same order of execution I want. Now, I can call addNSquare() function with two values and it'll do it's the best job by executing all three functions in the order I passed functions as arguments.
This snippet helped me to call multi functions in series at many scenarios, so, I thought to share it with you guys too. I hope you liked my explanation (if yes, hit like ❤️ button ) and if you found it informative then do follow from here because I'll learn and share every day.😋
Also follow/subscribe me on my social media account to connect with me : twitter, youtube
Top comments (0)