Lodash card with muted function

Can I use lodash to iterate over a collection and pass an element 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. This is how I thought it 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 ]

      

+3


source to share


3 answers


What you're basically trying to do here is the "curry" function x

that lodash supports with curry () . The curried function is a function that can take its arguments one at a time: if you don't supply the full set of arguments, it returns a function that expects the remaining arguments.

This is what curry 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 curry version:

console.log(_.map([1,2,3], _.curry(x)(10))); //Prints [11,12,13]

      

(As pointed out in the comment to the question, Function.prototype.bind

can also be used for currying, but if you are already using lodash you can use something specific for the task)

+6


source


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) }));

      

+4


source


Of course the closure is awesome! Just create a function that "closes" (wraps) your function x

and passes it 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));

      

0


source







All Articles