javascript - 来自 compose 函数的 Javascript Reduce
问题描述
我被困在一个在线课程的问题上,我试图向自己解释这个问题。我理解“compose”函数/想法以更简单的格式做什么,但是当涉及到为函数工厂应用 reduce 并在每个函数上运行 compose 时,我似乎感到困惑。希望有经验的人可以更清楚地向我解释“return fns.reduce(compose)”行是怎么回事,以及它是如何一次实现这些功能的?一旦在底部调用函数,每个函数是否轮流成为“累加器”,然后是 reduce 中的“当前”?
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})
)
解决方案
上面的答案已经足够好了,但是对于函数的更合乎逻辑reduce
的理解方法compose
。
// reduce return : (...args) => prev(curr(...args));
// f' : (...args) => f(g(...args));
// f'' : (...args) => f'(h(...args)); (...args) => f(g(h(...args)))
// f''' : (...args) => f''(j(...args)); (...args) => f(g(h(j(...args))))
// f'''' : (...args) => f'''(k(...args)); (...args) => f(g(h(j(k(...args)))))
function compose(f, g) {
return function(...args) {
return f(g(...args))
}
}
function composeAll(...fns) {
return fns.reduce(compose) // return function is (...args) => f(g(h(j(k(...args)))))
}
function f(x) {return x+'1'}
function g(x) {return x+'2'}
function h(x) {return x+'3'}
function j(x) {return x+'4'}
function k(x) {return x+'5'}
let result = composeAll(k, j, h, g, f)('cho');
console.log(result); // cho12345
前五行注释解释了函数的reduce
返回值会发生什么composeAll
。
f'' : (...args) => f'(h(...args)); (...args) => f(g(h(...args)))
表示(...args) => f'(h(...args))
与(...args) => f(g(h(...args)))
我将这些表示为f'
您需要区分 reduce 回调函数,reduce 回调函数中的f, g
(第 9 行)与composeAll
'sf
和g
arguments 的值不同(第 14 行)
推荐阅读
- javascript - 我什么时候应该在我的 react 应用程序中使用 Redux?
- protractor - 如何在量角器黄瓜中执行软断言
- flutter - 如何从颤振中的时间戳值中仅获取日期和时间值
- amazon-web-services - 有没有办法将多个请求/触发表单 SQS 连接到单线程 lambda 函数?
- r - 如何更改 ggforest(或 coxph 回归图)中的绘图大小?
- c++ - 使用&符号后跟下划线命名的变量是什么意思?
- python - 如何写入文本文件python 3?
- angular - Ag 网格图标标题
- vba - 保存文件而不指定驱动器位置
- java - 作业完成后 Spring Boot 重启应用