Curry Lodash的功能,奇怪的行为

Curry Lodash functions, strange behaviour

本文关键字:Lodash 功能 Curry      更新时间:2024-04-01

我试图伪造一个lodash函数,但我得到了一些奇怪的行为。基本上:

function(item){return _.curryRight(myFunction)('const')(item)}

与不同

_.curryRight(myFunction)('const')

我的猜测是,问题的出现是因为lodash中的函数具有不同的arity,无论你想将它们链接起来。

我用maxBy 观察到了这种行为

var myArrays = [[{variable : 1}, {variable : 2}], [{variable : 3}, {variable : 2}]];

这将返回预期结果

_.map(myArrays, function(item){return _.maxBy(item, 'variable')})
> [ { variable: 2 }, { variable: 3 } ]

如果我们在函数内curry maxBy,我们将获得相同的行为

_.map(myArrays, function(item){return _.curryRight(_maxBy)('variable')(item)})
> [ { variable: 2 }, { variable: 3 } ]

但是,以下内容不适用

_.map(myArrays, _.curryRight(_.maxBy)('variable'))
>[undefined, undefined]

所以基本上问题是,为什么最后一个方法的返回与前两个方法不同?

_.map(myArrays, _.curryRight(_.maxBy)('variable'))

这种情况不起作用,因为_.maxBy-的第二个参数必须是字符串"variable"。您可以访问开发工具中的lodash源代码,并通过它们找到方法_.maxBy。在此源文件中写入"console.log"并保存(Ctrl+s)。

function maxBy(array, iteratee) {
  console.log(arguments);
  return (array && array.length)
    ? baseExtremum(array, getIteratee(iteratee), gt)
    : undefined;
}

在控制台中运行

_.map(myArrays, _.curryRight(_.maxBy)('variable')) 

你看:

[Array[2], 1, Array[2], "variable"]

在方法_.maxBy中,首先传递了_.map迭代函数的所有参数https://lodash.com/docs#map在字符串"variable"之后。

用途:

_.map(myArrays, _.flow(_.identity,  _.curryRight(_.maxBy)('variable')));

它工作正常。抱歉我英语不好。

为了使curryRight工作,'variable'必须是第二个参数。

然而,当使用_.map函数时,'variable'作为第四个自变量到达。

这与执行_.map(array, parseInt)时发生的错误基本相同,结果将是意外的,因为parseInt将接收索引作为第二个参数,并将其用作基础