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!

0

4 Answers 4

20

Use an anonymous function:

A.map(function(a) {return doOpSingle2(a,theFlag);});
Sign up to request clarification or add additional context in comments.

2 Comments

+1, realised after posting my answer :)
TY! This will most likely be the only way to cover this task (apart from bind()). Thanks to the other answerers as well.
14

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

theFlag will be first argument though:

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

1 Comment

Love this bind() technique, thanks!
1

Use an anonymous function.

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

Comments

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.

3 Comments

javascript can already do currying with .bind though
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. ;)
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 ;).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.