Calling generic method multiple times with different parameters

javascriptlightning-web-components

Is there a way to make this code more optimized, so I have a generic method that process all the logic and it accepts the few parameters and then it adds the key/value to the object displayData

I'm repeating multiple times to call the myGenericMethod with different parameters, any thing that I can improve based on what I have here?

my generic method:

displayData = {};
myGenericMethod(param1, param2, param3) {
      //do something with parameters.....
      //.....get the data from db....
      //processed data
      //finally adding the 
      displayData[param1] = processed data
      displayData[param2] = processed data
      //.....
}

//call the myGenericMethod

this.myGenericMethod('aaa','bbb','ccc');
this.myGenericMethod('ddd','eee','eee');
this.myGenericMethod('fff','fff','fff');
this.myGenericMethod('ggg','ggg','ggg');

Best Answer

You can use Function.prototype.apply or Function.prototype.call to call the function. Here's an example with Function.prototype.apply:

[ ['aaa','bbb','ccc'], ['ddd','eee','eee'], ['fff','fff','fff'], ['ggg','ggg','ggg'] ]
  .forEach(params => this.myGenericMethod.apply(this, params))

The difference between the two is that apply accepts a list of parameters (as we're doing here), while call takes individual parameters.

In either case, we specify this as the first parameter, which sets the this inside the function call; we need this to access our controller's properties.

Related Topic