Search code examples
javascriptarraysfor-loopforeachsiesta

JavaScript: How to return a modified function with `forEach` or `for` loop?


I've a property name of items: which waits for a array list. The normal and running implementation of this code block is below;

// This usage works perfectly with `getFirstTest()` function
// And creates a list of Array fine!
harness.start(
    {
        group: 'UI Tests',
        testClass: Siesta.Test.ListClass,
        items: [
            {
              group: 'First Group',
              items: [
                  getFirstTest('Foo'),
                  getFirstTest('Bar'),
                  getFirstTest('Alpha'),
                  getFirstTest('Beta'),
                  getFirstTest('Zet')
              ]
            }
        ]
    }
);

but as you'll notice there are lots of iterative statements and therefore I've tried use forEach and for loops to state getFirstTest() function as dynamic but I can not render the array list as above, it's not throw any issue but can not create the list!

As well I need to able set several parameters on getFirstTest function:

e.g.: getFirstTest('Foo', 'SecondParam')

harness.start(
    {
        group: 'UI Tests',
        testClass: Siesta.Test.ListClass,
        items: [
            {
              group: 'First Group',
              items: this.firstGrpSubmodules
            }
        ]
    }
);

function firstGrpSubmodules () {
    let implementedCases = [
        'Foo', 'Bar', 'Alpha', 'Beta', 'Zet'
    ];

    // I've tried several ways to achive but couldn't
    // Usage 1: The for loop
    // for (let i=0; i<implementedCases.length; i++) {
    //       let submodules = implementedCases[i];
    //
    //       getFirstTest(submodules);
    // }

    // Usage 2: forEach
    // implementedCases.forEach(function(submodule) {
    //     getFirstTest(submodule);
    // });
}

What I'm missing here and how can i achieve for second implementation? Thanks in advance!


Solution

  • Use Array.prototype.map:

    harness.start({
      group: 'UI Tests',
      testClass: Siesta.Test.ListClass,
      items: [
        {
          group: 'First Group',
          items: ['Foo', 'Bar'].map(getSalesTest),
        }
      ]
    });