9

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!

syntaxerror
  • 661
  • 2
  • 6
  • 24

4 Answers4

20

Use an anonymous function:

A.map(function(a) {return doOpSingle2(a,theFlag);});
NorthDecoder
  • 47
  • 1
  • 8
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
14

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

theFlag will be first argument though:

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

Esailija
  • 138,174
  • 23
  • 272
  • 326
1

Use an anonymous function.

var y = A.map(function(x){doOpSingle2(x,theFlag);});
UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
1

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.

Tyler
  • 21,762
  • 11
  • 61
  • 90
  • 1
    javascript can already do currying with `.bind` though – Esailija Jun 03 '12 at 17:33
  • THIS is the very problem. It would just be overkill to use an external library for this little problem. But still, thanks anyway for this approach. In a _real_ big project, I might need this technique someday. ;) – syntaxerror Jun 03 '12 at 20:27
  • That's why I said "if you happen to be using Closure" instead of "you should drop everything right now and start using Closure" the way [some people do](http://meta.stackexchange.com/a/19492/65977) ;). – Tyler Jun 04 '12 at 02:07