Why at first I get 80 then 88 and then 90? Can anyone explain in detail what is happening in the compose
function?
const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
const sum = a => b => a b
const multiply = a => b => a * b
const addTransactionFee = sum(2)
const addTax = multiply(1.1)
const addMonthlyPromotion = multiply(0.8)
const log = a => {
console.log(a)
return a
}
const paymentAmount = compose(
log,
addTransactionFee,
log,
addTax,
log,
addMonthlyPromotion
)(100)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can use recursion instead. This way the order of functions is preserved (and not reversed).
const recursion = (value, func, ...fns) =>
func ? recursion(func(value), ...fns) : value;
const paymentAmount = (amount) =>
recursion(
amount,
log,
addTransactionFee,
log,
addTax,
log,
addMonthlyPromotion,
log
);
CodePudding user response:
The compose function with the loop of reduce..take the right function (the latest (addMonthlyPromotion()
)) and make the result of 100 * 0.8 so you have 80 at the first loop.
Then you have the second loop with the second function (addTax()
) it multiply's the previous result of (80) with 1.1 so 88.
And the final loop and the 3rd one of reduce with the function (addTransactionFee()
) add 2 in your previous number so 90.
Now the compose function goes from right to left of looped function and do the calculations.