JS callback using map() with a function that has one additional parameter [duplicate]

I'm trying to find a way to use JS's Array.prototype.map() functionality with a function that has one additional parameter more (if possible at all, and I'd like to avoid having to rewrite built-in Array.prototype.map()). This documentation is very good, but does not cover the "one-or-more-additional-parameter" case:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map

function doOpSingle(elem)
{
 // do something with one array element
}

var A = ["one", "two", "three", "four"];
var x = A.map(doOpSingle); // this will execute doOpSingle() on each array element

So far, so good. But what if the function in question has two parameters, like e. g. a flag you might want to OR to it (think of bit masks)

function doOpSingle2(arrelem,flag)
{
 // do something with one array element
}

var A = ["one", "two", "three", "four"];
var theFlag = util.getMask(); // call external function
var y = A.map(doOpSingle2(theFlag)); // this does not work!

Any solutions should do without for loops, of course, because that's why we have map(), to make our code cleaner w/getting rid of these!

Answers:

Answer

Use an anonymous function:

A.map(function(a) {return doOpSingle2(a,theFlag);});
Answer

A.map(doOpSingle2.bind(null, theFlag))

theFlag will be first argument though:

function doOpSingle2( flag, elem ) { ... }

Answer

Use an anonymous function.

var y = A.map(function(x){doOpSingle2(x,theFlag);});
Answer

Edit: Nevermind, you don't really need Closure for this. See Esailija's answer.

There is another option, if you happen to be using the Closure library. First you have to rewrite doOpSingle2 so that the flag is first:

function doOpSingle2(flag, arrelem)
{
 // do something with one array element
}

then you can do

var y = A.map(goog.partial(doOpSingle2, theFlag));

goog.partial partially applies the function, so goog.partial(doOpSingle2, theFlag) is equivalent to this function:

function(arrElem) {
  return doOpSingle2(theFlag, arrElem);
}

In this particular case, I probably wouldn't recommend this approach, but there might be similar situations where it works well.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.