首页 > 解决方案 > 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: []})
}

标签: javascriptfunctional-programming

解决方案


如果您举一个最小的工作示例并可视化输出结构,也许会有所帮助:

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 一个空数组。


推荐阅读