Member-only story
Functional Programming concept with Javascript (Coding by Composing)
JS Composition is like function husbandry. It’s like combining and mashing multiple functions together to spawn or build a brand new one. As simple as that.
Straight to the example :
var makeUppercase = function(x){
return x.toUpperCase();
}var fullStop = function(x){
return x + '.';
}var word = compose(makeUppercase, fullStop);word('hello'); // => 'HELLO.'
Here ‘makeUppercase’ and ‘fullStop’ are two separate function . By using compose function we combined them together and build a new one for an output where we performed two task; Making the ‘word’ uppercase and adding a fullstop at the end.
Mathematical Composition:
In mathematics “f composed with g” is the function that given x
, returns f(g(x))
. We have to read these from right-to-left . Like first we’ll get ‘the value’ of g(x) then f(‘the value’)!
compose(f, g) --> f(g(x))
Now let’s go through the simplest compose that is used earlier in this tutorial:
var compose = function(f, g) {
return function(x) {
return f(g(x));
};
};