I works by calling the function from inside to the outer funtion. As illustration, the function and their call with paramters and their following calls.
five()
expression(5)
5
times(5)
function with closure over x = 5
seven(function)
expression(7, function)
function(7)
35
At the end, you find the same result, but with an array of the functions in a reversed order. The functions get called with the accumulator, which returns the result of the function call.
This approach is an actual implementation of the maybe later (or never) you can use the actual experimental pipeline operator |>
, which has the following syntax:
expression |> function
Or with your functions:
undefined |> five |> times |> seven
function expression(number, operation) {
console.log('expression');
if (!operation) return number;
return operation(number);
}
function five(operation) {
console.log('five');
return expression(5, operation);
}
function seven(operation) {
console.log('seven');
return expression(7, operation);
}
function times(x) {
console.log('times');
return function(y) {
return y * x;
}
}
console.log(seven(times(five()))); // 35
console.log([five, times, seven].reduce((value, fn) => fn(value), undefined))