简体   繁体   中英

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?

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)
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM