Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash Map with mulitvariable function

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 ]
like image 988
Terry Avatar asked Dec 20 '22 04:12

Terry


1 Answers

What 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 comment 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)

like image 79
Retsam Avatar answered Dec 30 '22 03:12

Retsam