admin管理员组文章数量:1287935
Is it possible to use lodash to iterate over a collection and pass the item to a function that requires two (or more) arguments? In the following example, the function should take two values and add them. The map should take an array and add 10 to each. The following is how I thought this worked:
function x (a, b) {
return a + b
}
var nums = [1, 2, 3]
console.log(_.map(nums,x(10)))
--->ans should be [11, 12, 13]
--->actually is [ undefined, undefined, undefined ]
Is it possible to use lodash to iterate over a collection and pass the item to a function that requires two (or more) arguments? In the following example, the function should take two values and add them. The map should take an array and add 10 to each. The following is how I thought this worked:
function x (a, b) {
return a + b
}
var nums = [1, 2, 3]
console.log(_.map(nums,x(10)))
--->ans should be [11, 12, 13]
--->actually is [ undefined, undefined, undefined ]
Share
Improve this question
asked May 17, 2015 at 14:30
TerryTerry
7851 gold badge8 silver badges20 bronze badges
1
-
2
Partial application,
_.map(nums, x.bind(null, 10))
, or curryx
. – elclanrs Commented May 17, 2015 at 14:36
3 Answers
Reset to default 7What you're essentially trying to do here is "curry" the x
function, which lodash supports via curry(). A curried function is one that can take its arguments one at a time: if you don't provide a full set of arguments, it returns a function expecting the remaining arguments.
This is what currying looks like:
function x(a,b) {
return a + b;
}
x = _.curry(x); //returns a curried version of x
x(3,5); //returns 8, same as the un-curried version
add10 = x(10);
add10(3); //returns 13
So your original code is very close to the curried version:
console.log(_.map([1,2,3], _.curry(x)(10))); //Prints [11,12,13]
(As was pointed out in the ment on the question; Function.prototype.bind
can also be used for currying, but if you're already using lodash, you might as well use something specific to the task)
You can do it like this:
var numbers = [1, 2, 3];
function x(value, number) {
return value + number;
}
console.log(_.map(numbers, function(value) { return x(value, 10) }));
Sure, closure is awesome! Just make a function that "closes" (wraps) your x
function and passes 10 as its second argument.
function x (a, b) {
return a + b;
}
function addTen (number) {
return x(numberToAddTo, 10);
}
var nums = [1, 2, 3];
console.log(_.map(nums, addTen));
本文标签: javascriptLodash Map with mulitvariable functionStack Overflow
版权声明:本文标题:javascript - Lodash Map with mulitvariable function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741331511a2372792.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论