How to write your own pipe function in JS
Javascript is so dynamic that we can choose many ways to write our code. Why not doing it the Functional programming way?
What is function piping?
Do you remember in high school, in math class, that you had two functions —
f(x) and g(x).
And then you could create a new function:
h(x) = f(g(x)).
The new function would accept an argument and pass that argument two g(x) and then pass the evaluated value to the next function = f(g).
So, function piping is the same base idea, you create a new function that will “pass” trough several smaller functions.
Writing pure
In the functional world we looove writing pure functions.
A function consider pure if:
1. It gets all the parameters that it needs (doesn’t use any global variables or class members)
2. Always return the same output for a given input
3. Doesn’t have any side effect (server calling, db fetching, DOM rendering etc)
The pure functions has many advantages:
1. It’s testable! No more setup or writing mock class
2. It’s cache-able- those function are deterministic, why calculating the same input more then once?
There is a cool pattern called memoize, please check it out.
And the advantage we are here for is:
3. It’s compose-able! you can pipe as many functions as you like to create a more complex function (or even an entire feature).
The reduce function
Since we’ll creating the pipe function based on “Array.reduce()”, I’ll explain it shortly.
reduce() will take the elements in the array, process them and return one element. This one element can be any thing, even a function as we’ll see in the next section.
// Sum function, gets an array and returns the sum
// es5 style, mabye it's clearer
function sum_es5(arr) {
arr.reduce(function(acc,curr) {
return acc + curr
}, 0
}// The same function written in es6
const sum = arr =>
arr.reduce((acc, curr) => acc + curr, 0)const mul = arr =>
arr.reduce((acc, curr) => acc * curr, 1)sum([1,2,3]) // 6
mul([2,3,4]) // 24
Let’s break it down.
The reducer function gets two arguments:
First
A function, this function itself gets two arguments, an accumulator and the current value. The first one, holds the aggregated value we’ve calculated so far. The second, is the current element in our array.
Second
The initial value. The accumulator will be initialize with this value.
So now it’s easy to understand our Sum function.
The initial value is 0, of course, and each iteration we return the sum of the aggregated value so far and the current array element.
Create the pipe function
Dealing with more than one arguments
As we saw in our pipe function, we handle well with multiple arguments passed to our first function.
What about multiple-arguments function that is not the first function?
There is a beautiful design pattern in the functional world called- curry, that helps us solve this problem. I will cover it in another article.