NodeJS:重构一个long switch语句

时间:2017-12-26 13:26:24

标签: javascript node.js switch-statement

我有一个很长的开关声明,我需要用更多的练习声明替换它,请帮助:

switch (global.testSuite) {
    case "cleanCache":
      testSenarios.cleanCache();
      break;
    case "setting":
      testSenarios.setting();
      break;
    case "installExtensions":
      testSenarios.installExtensions();
      break;
    case "addIndividualContact":
      testSenarios.addIndividualContact();
      break;
    case "addContact":
      testSenarios.addContact();
      break;
    case "add":
      testSenarios.add();
      break;
}

2 个答案:

答案 0 :(得分:11)

如果您在testSenarios中只有有效的属性,则可以进行检查并使用括号property accessor调用该函数。

if (global.testSuite in testSenarios) {
     testSenarios[global.testSuite]();
}

或者,如果您有更多属性而不是函数,则可以检查function

if (typeof testSenarios[global.testSuite] === 'function') {
     testSenarios[global.testSuite]();
}

答案 1 :(得分:-2)

可以使用带有键值对的Object轻松替换开关案例。

//Define a object 
const testSuite = {
    cleanCache : testSenarios.cleanCache,
    setting : testSenarios.setting
    ......
    ....
}

//Then Replace the switch-case block with a single call
testSuite[global.testSuite]()

您甚至可以添加'默认'用于处理默认情况的密钥。