I am stuck on a problem on an online course that I am trying to explain this to myself. I understand what the "compose" function/ idea does in a simpler format but when it comes to applying reduce for a factory of functions and running compose on each function seems to be confusing to me. Hoping someone with experience can explain to me more clearly what is going on in terms of the "return fns.reduce(compose)" line and how it implements these functions one at time? Is each function taking turns being the "Accumulator" and then the "current" in reduce once the function is invoked at the bottom?
const user = {
user: 'Jennnifer',
active: true,
cart: [],
purchases: []
}
const compose = (f, g) => (...args) => f(g(...args));
function purchaseItem(...fns){
return fns.reduce(compose)
// return Object.assign({}, user, {purchases: item})
}
//Receives a user, and the item
function addItemToCart(user, item){
//Create a variable and concat the empty cart of the user object to add the item to the cart key.
const updateCart = user.cart.concat(item);
return Object.assign({}, user, { cart: updateCart });
}
function applyTaxToItems(user){
const { cart } = user;
const taxRate = 1.3;
const updatedCart = cart.map(item => {
return {
name: item.name,
price: item.price * taxRate
}
})
return Object.assign({}, user, { cart: updatedCart})
}
function buyItem(user){
return user
}
function emptyCart(user){
return user
}
//Invoke Function:
console.log(purchaseItem
(
emptyCart,
buyItem,
applyTaxToItems,
addItemToCart
)(user, { name: 'Laptop', price: 200})
)