javascriptobjectjavascript-objectsjsobject

Redundant code for objects name-values in JavaScript


I defined a js object whose name-value pairs are function expressions with more or less same function definition. The key names of the object match the functions of the module imported from outside.

const myModule = require('some_module');    //some module imported from outside

const myObj = {};

myObj.abc = (param1, param2, param3) => {
  myModule.abc(param1, param2, param3);
  // some algorithm (say algo)
}

myObj.xyz= (param1, param2, param3) => {
  myModule.xyz(param1, param2, param3);
  // same algorithm (algo)
}

myObj.pqr= (param1, param2, param3) => {
  myModule.pqr(param1, param2, param3);
  // same algorithm (algo)
}

//All the three names (abc, xyz, pqr) have nearly same function definitions.

My question is; is there any better way to reduce the lines of code because the code seems redundant?


Solution

  • I'd iterate over an array of method names instead to define the functions:

    const methods = ['abc', 'xyz', 'pqr'];
    for (const key of methods) {
      myObj[key] = (param1, param2, param3) => {
        myModule[key](param1, param2, param3);
        // some algorithm (say algo)
      };
    }