javascript - Javascript - 将 compose 与 reduce 一起使用
问题描述
我正在学习使用 javascript 进行函数式编程。我了解到reduce需要2个参数。累加器和实际值,如果我们不提供初始值,则使用第一个参数。但我不明白这些purchaseItem
函数在下面的代码中是如何工作的。谁能解释一下。
const user = {
name: 'Lachi',
active: true,
cart: [],
purchases: []
}
let history = []
const compose = (f, g) => (...args) => f(g(...args))
console.log(purchaseItem(
emptyCart,
buyItem,
applyTaxToItems,
addItemToCart
)(user, {name: 'laptop', price: 200}))
function purchaseItem(...fns) {
console.log(fns)
return fns.reduce(compose)
}
function addItemToCart (user, item) {
history.push(user)
const updatedCart = user.cart.concat(item)
return Object.assign({}, user, { cart: updatedCart })
}
function applyTaxToItems(user) {
history.push(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) {
history.push(user)
return Object.assign({}, user, { purchases: user.cart })
}
function emptyCart(user) {
history.push(user)
return Object.assign({}, user, {cart: []})
}
解决方案
如果您举一个最小的工作示例并可视化输出结构,也许会有所帮助:
const comp = (f, g) => x => f(g(x));
const inc = x => `inc(${x})`;
const sqr = x => `sqr(${x})`;
const id = x => `id(${x})`;
const main = [sqr, inc, inc, inc].reduce(comp, id);
console.log(main(0)); // id(sqr(inc(inc(inc(0)))))
请注意,我们需要id
允许 redicung 一个空数组。
推荐阅读
- python - re.sub 仅用于捕获的组
- django - Annotating data in Django Templates
- chapel - 不断收到“错误:无法从迭代器分配给 int(64)”
- kubernetes - Minikube 可重试失败:创建:创建机器时出错:机器创建期间驱动程序出错:hyperkit 崩溃!命令行:
- arrays - numpy.genfromtxt ,列之间的空间不均匀会导致 dtype 错误吗?
- navigation - TYPO3 中的响应式菜单
- nvm - 为什么 Ubuntu 上的其他用户使用我的 $NVM_DIR?
- angular - 在 Angular2 中的 setTimeout 之后从 Viewchild 元素中删除类
- reactjs - React Hooks UseEffect 不适用于我的 cacheImage 组件
- c# - MvxGridView ItemClick 未触发