KLôN KLôN - 4 months ago 7
Javascript Question

generate dynamically an array of functions integrating a parameter?

I have a function that takes an index as a parameter :



function awesomeFunction(index) {
console.log(index); // does awesome stuff depending on the index
}





Now, I would like to dynamically create an array of such functions, each one using NO PARAMETER AT ALL. Here is what I have in mind :



function generateAwesomeFunction(index) {
return function () {
console.log(index);
}
}

var awesomeArray = [];

for (var i=0 ; i<something ; i++) {
awesomeArray.push(generateAwesomeFunction(i));
}





In my twisted mind, the output
awesomeArray
should contain functions, none of these takes any parameter, but all of these do different things because the
index
is INTEGRATED in the function when generated. For instance, the following calls execute a different code :



awesomeArray[0]();
awesomeArray[1]();
// and so on...





A running example is :



function awesomeFunction(index) {
console.log(index); // does awesome stuff depending on the index
}

function generateAwesomeFunction(index) {
return function () {
console.log(index);
}
}

var awesomeArray = [];

for (var i=0 ; i<5 ; i++) {
awesomeArray.push(generateAwesomeFunction(i));
}

awesomeArray[0](); // 0
awesomeArray[1](); // 1
awesomeArray[2](); // 2
// and so on...





Questions :


  1. Does it work ? ---> YES !

  2. Is there a BETTER way to generate that array of functions ?


Answer

Use bind and partial application to create a new function from awesomeFunction that will always be invoked with a specific index parameter. In this case, it doesn't matter what value of this you foward to the function.

You don't need the generateAwesomeFunction function.

function awesomeFunction(index) {
  console.log(index); // does awesome stuff depending on the index
}
var awesomeArray = [];

for (var i=0 ; i<5 ; i++) {
  awesomeArray.push(awesomeFunction.bind(this, i));  
}

awesomeArray[0](); // 0
awesomeArray[1](); // 1
awesomeArray[2](); // 2

Comments