Curry Lodash 函数,奇怪的行为
Curry Lodash functions, strange behaviour
我正在尝试 curry 一个 lodash 函数,但出现了一些奇怪的行为。基本上:
function(item){return _.curryRight(myFunction)('const')(item)}
与
不一样
_.curryRight(myFunction)('const')
我的猜测是问题的出现是因为 lodash 中的函数具有不同的元数,无论您是否要链接它们。
我观察到 maxBy
的行为
var myArrays = [[{variable : 1}, {variable : 2}], [{variable : 3}, {variable : 2}]];
这是returns预期的结果
_.map(myArrays, function(item){return _.maxBy(item, 'variable')})
> [ { variable: 2 }, { variable: 3 } ]
如果我们在函数内部柯里化 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 iteratee 函数 https://lodash.com/docs#map 的所有参数,然后是字符串 'variable'.
使用:
_.map(myArrays, _.flow(_.identity, _.curryRight(_.maxBy)('variable')));
它工作正常。
抱歉我的英语不好。
为了 curryRight
工作,'variable'
必须是第二个参数。
但是,当使用 _.map
函数时,'variable'
作为第四个参数到达。
这基本上与执行 _.map(array, parseInt)
时发生的错误相同,结果将是意外的,因为 parseInt
将接收索引作为第二个参数并将其用作基础
我正在尝试 curry 一个 lodash 函数,但出现了一些奇怪的行为。基本上:
function(item){return _.curryRight(myFunction)('const')(item)}
与
不一样_.curryRight(myFunction)('const')
我的猜测是问题的出现是因为 lodash 中的函数具有不同的元数,无论您是否要链接它们。
我观察到 maxBy
的行为var myArrays = [[{variable : 1}, {variable : 2}], [{variable : 3}, {variable : 2}]];
这是returns预期的结果
_.map(myArrays, function(item){return _.maxBy(item, 'variable')})
> [ { variable: 2 }, { variable: 3 } ]
如果我们在函数内部柯里化 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 iteratee 函数 https://lodash.com/docs#map 的所有参数,然后是字符串 'variable'.
使用:
_.map(myArrays, _.flow(_.identity, _.curryRight(_.maxBy)('variable')));
它工作正常。 抱歉我的英语不好。
为了 curryRight
工作,'variable'
必须是第二个参数。
但是,当使用 _.map
函数时,'variable'
作为第四个参数到达。
这基本上与执行 _.map(array, parseInt)
时发生的错误相同,结果将是意外的,因为 parseInt
将接收索引作为第二个参数并将其用作基础