使用lodash _.flow进行过滤、减少、映射



作为一个在函数式编程中应用lodash库的初学者,我发现._flow不能执行所放入的函数。我的问题是如何在流中应用map、reduce或filter ?或者我做错了什么?如有任何帮助,不胜感激。

例如:

const _=require('lodash');
const scores = [50, 6, 100, 0, 10, 75, 8, 60, 90, 80, 0, 30, 110];
const newArray=_.filter(scores,val=>val<=100);
const newArray2=_.filter(newArray,val=>val>0);
console.log(newArray2);
// the output is
/*[
50,  6, 100, 10, 75,
8, 60,  90, 80, 30
]*/

然而,当我把它变成两个独立的函数并放入流中时,它不做任何事情。

const newRmvOverScores=_.filter(val=>val<=100);
const newRmvZeroScores=_.filter(val=>val>0);
const aboveZeroLess100=_.flow(newRmvOverScores,newRmvZeroScores)(scores);
console.log(aboveZeroLess100);
// the output is:
/*[
50,  6, 100,  0, 10, 75,
8, 60,  90, 80,  0, 30,
110
]*/

我找到了几个参考资料:

[1]使用lodash,为什么flow中的map方法不工作?[2] https://lodash.com/docs/4.17.15流

两个问题:

  • 在定义newRmvOverScoresnewRmvZeroScores时,实际上已经执行了_.filter,并且没有集合参数。它们应该是函数
  • _.flow期望一个函数数组,但您没有提供一个数组,也不是参数函数(因为前一点)

下面是修改后的脚本:

const scores = [50, 6, 100, 0, 10, 75, 8, 60, 90, 80, 0, 30, 110];
const newRmvOverScores = scores => _.filter(scores, val=>val<=100);
const newRmvZeroScores = scores => _.filter(scores, val=>val>0);
const aboveZeroLess100 = _.flow([newRmvOverScores,newRmvZeroScores])(scores);
console.log(aboveZeroLess100);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

最新更新