繁体   English   中英

当函数返回时,reduce 函数如何工作? 还想了解更多关于作曲和作曲的信息

[英]How does the reduce function work when a function is returned? Would also like to know more about compose and composition

以下代码以函数方式编写。 有一个要进行购买的用户对象。 过程如下:将商品添加到购物车,添加税款,购买商品并将其推送到用户的购买历史数组中。 然后最后原来的购物车被清空。 这一切都是通过使用传递了 compose 函数的 reduce 函数来完成的。

我很难理解的是 reduce 函数在这种情况下是如何工作的。 根据我的理解,compose 函数是作为reduce 的回调函数传入的。 在 compose 函数中,f 表示累加器,g 表示数组中的一项。

 const user = {
  name: 'Kim',
  active: true,
  cart: [],
  purchases: []
}

const compose = (f,g) => (...args) =>  {
  console.log(1, f);
  console.log(2, g);
  return f(g(...args));
  }

// The below code is commented out so that I can visualize it in a more simple manner
//purchaseItem (
 // emptyCart,
 // buyItems,
  //applyTaxToItems,
 // addItemToCart
//)(user, {name: 'laptop', price: 244});

function purchaseItem(...fns) {
  console.log(fns);
  return fns.reduce(compose);
}

// Here is each piece broken down to be passed into reduce and the arguments the compose function takes
console.log([emptyCart , buyItems, applyTaxToItems, addItemToCart].reduce(compose)(user, {name: 'laptop', price: 244}));

function addItemToCart(user, item) {
  const updateCart = user.cart.concat(item);
  return Object.assign({}, user, { cart: updateCart });
}

function applyTaxToItems(user, item) {
  return user
}

function buyItems(user, item) {
  return user
}

function emptyCart(user, item) {
  return user
} 

输出如下:

1 [Function]
2 [Function: addItemToCart]
1 [Function]
2 [Function: applyTaxToItems]
1 [Function: emptyCart]
2 [Function: buyItems]
{ name: 'Kim',
  active: true,
  cart: [ { name: 'laptop', price: 244 } ],
  purchases: [] }  

我试图映射 f 和 g 元素的流向。 我知道 f 将保存 compose 函数返回的任何值,但为什么初始值是匿名函数。 此外,为什么 item 元素从数组中的最后一个元素开始并向后工作? 我也很困惑为什么emptyCart 函数在reduce 的最后一个循环中变成f 值。 如果有人能向我解释这一点,我将不胜感激。 谢谢你。

您的日志没有正确映射执行流程。

您首先记录fg记录g ,但是对于f(g(x)) ,首先计算gg计算f f(g(x)可以读作“x 的 g 之后的 f”或“x 的 g 的 f”。

以同样的方式,当您使用像f(g(...x))这样的 reducer 来减少函数数组时,它们将以相反的顺序进行计算,因为结果函数的行为类似于f(g(h(x)))

有关更多解释,请参阅下面的代码。 compose2与您的compose函数相同,但具有更重的日志记录。

如果您运行下面的代码,您可能会更好地了解发生了什么。 为了评估由归约/组合创建的函数,我们评估形式为f(g(...args))多个函数。

注意g(...args)的结果如何在最终结果向下传播之前全部向上传播。

 const compose2 = (f, g, i) => { const name = `${f.name} after ${g.name}`; const h = {[name]: (...args) => { console.log(i, 'f:', f.name); console.log(i, 'g:', g.name); console.log(i, 'args to g:', ...args); console.log(i, 'g(...args):', g(...args)); console.log(' '); const res = f(g(...args)); console.log(i, 'result:', res); return res; }}[name]; return h; } const f_xe = x => x + 'e', f_xd = x => x + 'd', f_xc = x => x + 'c', f_xy = (x, y) => x + y; console.log([f_xe, f_xd, f_xc, f_xy].reduce(compose2)('a','b'));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM