Samantha J T Star
Samantha J T Star

Reputation: 32778

How can I make an array of object in my function parameter call a function for each object?

I created the following checkGrid function which takes a count and then another two parameters. It's a solution which hardcodes in the selectOption calls and is not very flexible:

checkGrid = function(expectCount, typeParam, selectParam) {

   it('Check', function () {
      selectOption('examTypeSelect', typeParam).click();
      selectOption('examStatusSelect', selectParam).click();
    });

}
checkGrid(10, '*', '*');

Now I would like to make this more flexible so that it accepts arguments for any number of selectOption functions. So I was thinking of something that I could call like this. HEre what I would need is for the checkGrid function to call the selectOption three times:

checkGrid(10, [{'examTypeSelect','*'}
               {'examStatusSelect', '*'},
               {'abcSelect','29'}]);

How could I take an array object that's the second parameter for checkGrid and make it so that it calls any number of selectOption functions depending on how many elements there are in the array?

Upvotes: 0

Views: 40

Answers (1)

Jon
Jon

Reputation: 437336

By using a loop over the array and .apply to call each function with a variable number of arguments.

checkGrid = function(expectCount, stuff) {
    it('Check', function () {
        for (var i = 0; i < stuff.length; ++i) {
            selectOption.apply(this, stuff[i]).click();
        }
    });
}

You would call this not with your proposed syntax (which is invalid), but like

checkGrid(10, [
                ['examTypeSelect','*'],
                ['examStatusSelect', '*'],
                ['abcSelect','29','and','perhaps','more','parameters']
              ]
          );

Finally, it's unclear what expectCount is supposed to do but I left it there because your original code presumably does something with it.

Upvotes: 2

Related Questions