Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement an array of functions in JavaScript?

I am still new to JavaScript. I need to code a 20 x 20 matrix pair of functions. All my functions take in a number in and return a number (i.e, same signature). For example, Myfunctions[1][2] should return me a pair of functions I could call in the code.

In Java, I would typically implement an array of 20 x 20 objects where each object would implement two functions. But, is this possible in JavaScript? If not, how should I proceed to get something similar? If I need two matrix to simulate the pair, this is OK too.

like image 447
Jérôme Verstrynge Avatar asked Dec 06 '22 18:12

Jérôme Verstrynge


1 Answers

Since functions are objects in JavaScript, you can define an array of them quite easily.

function foo () { ... }
function bar () { ... }
function baz () { ... }

var fns = [foo, bar, baz];

The signature does not matter at all.


From there you can start dynamically generating functions in a loop, rather than explicitly declaring each one:

function generator(n)
{
    return function ()
    {
        return n*n;
    };
}

var squareFuncs = [];

for (var i=0; i<10; i++)
{
    squareFuncs.push(generator(i));
}

Then you can build up arrays of arrays of functions (just like any other object, remember):

function anotherGenerator(a, b)
{
    return function ()
    {
        return a+b;
    };
}

var sumFuncs = [],
    temp,
    i,
    j;

for (i=0; i<20; i++)
{
    temp = [];
    for (j=0; j<20; j++)
    {
        temp.push(anotherGenerator(i, j));
    }
    sumFuncs.push(temp);
}

Now sumFuncs is a two-dimensional array (really, an array of arrays) of functions which compute the sum of the coordinates of that function in the matrix. That probably sounds more complicated than it really is, so here's an example:

var foo = sumFuncs[7][2],
    sum = foo();
console.log(sum); // prints 9

Related:

  • Can I store JavaScript Functions in arrays?
  • Javascript Array of Functions
like image 58
Matt Ball Avatar answered Dec 31 '22 14:12

Matt Ball