0

I'm trying to create a function that returns an array with n elements, that are all the same function (this array will later be used to call those functions in parallel using async).
I can easily loop over an array and add the function to each element, but was wondering if I can do it in one line, using map:

//the function to point to
var double = function(x) {
    return x*2;
};

//this function will create the array - just a filler for a one-liner
var createConsumersArray = function(numOfConsumers) {
    var consumers = (new Array(2)).map(function(x){return double;});
    return consumers;
};

var t = createConsumersArray(2);
console.log(t);     //prints [,]
console.log(t[1](2));   //TypeError: Property '1' of object , is not a function

If I pre-fill the array with constants, the map works, i.e.:

var x = [1,2,3];
console.log(x.map(function(x){return double;})); //prints [ [Function], [Function], [Function] ]
console.log(x[1](2)); //prints 4

How can I accomplish filling an array with an identical function in the shortest way?

Traveling Tech Guy
  • 27,194
  • 23
  • 111
  • 159

2 Answers2

1

You have to change a little.

var createConsumersArray = function(numOfConsumers) {
    var consumers = Array.apply(null, Array(numOfConsumers)).map(function(){return double;});
    return consumers;
};
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • 2
    Would you mind to explain [how this works](http://stackoverflow.com/q/18947892/1048572)? – Bergi Jun 17 '14 at 17:43
1

This is more functional programming. If you'd like to program in this style, I'd recommend you look at underscore.js. Here's an example of a range function:

_.range(10);
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

For your use case you would do:

_.map(_.range(4), function(num){ return double; });

Here's the corresponding jsfiddle example:

Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
  • I usually use lodash in my projects, and your solution definitely works, so +1. However, I was trying for a pure JS solution this time. – Traveling Tech Guy Jun 17 '14 at 17:59
  • I see - FYI on your future projects - this code is 100% compatible with lodash: http://lodash.com/docs#range, http://lodash.com/docs#map – Martin Konecny Jun 17 '14 at 18:19
  • Thanks @Martin. I'm aware of their compatibility (in fact, I started with underscore and transitioned to lodash). It's just that on this particular project, I'm trying to minimize external resources. But your answer still stands. – Traveling Tech Guy Jun 17 '14 at 23:35