Search code examples
javascriptfunctionextjsargumentsfactory-pattern

JavaScript: How to run a function several time with different arguments?


I'm using ExtJS framework and a run one method multiple times with different parameters.

I'm looking a way to make it more consist, easy and maintainable and I guess just vanilla Javascript solutions could handle this?

I've tried to collect each param into array and using Array.map() as well forEach() methods but I couldn't handle it.

Thanks for advance.

//ExtJS class:
Ext.define('MyApp.FooClass', {
    extend: 'Ext.panel.Panel',

    items: [
        MyApp.createFooCard('Func1Param1', 'Func1Param2', 'Func1Param3'),
        MyApp.createFooCard('Func2Param1', 'Func2Param2', 'Func2Param3'),
        MyApp.createFooCard('Func3Param1', 'Func3Param2', 'Func3Param3'),
    ]
});

As you'll notice I totaly use same method but different arguments for each of them.

//And here is related factory-function:
createFooCard: (bindValue, userCls, glyph, label) => {
        return {
            itemId: bindValue,
            userCls: userCls,
            glyph: MyApp.getGlyph(glyph),
            items: {
                xtype: 'infocardfld',
                fieldLabel: label,
                bind: '{' + bindValue + ' || "0"}'
            }
        }
    }

Solution

  • It works with Array.prototype.map to collect nested arrays and relaying those arrays with Spread syntax to run on factory-function. It should be:

    Ext.define('MyApp.FooClass', {
        extend: 'Ext.panel.Panel',
    
        items: [
                  ['Func1Param1', 'Func1Param2', 'Func1Param3'],
                  ['Func2Param1', 'Func2Param2', 'Func2Param3'],
                  ['Func3Param1', 'Func3Param2', 'Func3Param3']
               ].map(args => MyApp.createFooCard(...args));
        });