首页 > 解决方案 > 来自 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})
)

标签: javascriptecmascript-6reduce

解决方案


上面的答案已经足够好了,但是对于函数的更合乎逻辑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'sfgarguments 的值不同(第 14 行)


推荐阅读