compose
The compose
function takes other functions as its arguments and its responsibility is to run the functions in sequence and send the output of each function to the next function as the argument.
For example, if we want to write a function that takes a number and add it to 3
then multiply it by 4
and finaly divide it by 2
:
// We can write it in this way
const someOperation = number => {
const addResult = addToThree(number);
const multiplyResult = multiplyByFour(addResult);
const divideResult = divideByTwo(multiplyResult);
return divideResult;
}
// Or a more concise version of that
const someOperation = number =>
divideByTwo(multiplyByFour(addToThree(number)));
And as the number of operation be increased, it can kill the readability of code.
So in this kind of situation we can easy use compose
function to make it simpler for us.
const someOperation = compose( divideByTwo, multiplyByFour, addToThree );
console.log(someOperation(5)) // output> 16
But keep in mind that the compose
function runs the functions from right to left.