2017-12-26 5 views
0

긴 switch 문을 리팩토링 내가 더 많은 연습 문으로 대체 할 필요가 도움하십시오NodeJS : 나는 긴 <strong>스위치</strong> 문이

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

'testSenarios [global.testSuite]()' –

답변

11

당신이 testSenarios에서만 유효 속성이있는 경우, 확인을하고 괄호로 함수를 property accessor으로 호출 할 수 있습니다.

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

아니면 함수없이 많은 특성이있는 경우, 대신 function를 확인할 수 있습니다.

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

@Nina –

+0

@ MohamadTrabelsi, 감사합니다. –

-2

스위치 케이스는 키 - 값 쌍을 가진 객체로 쉽게 교체 할 수 있습니다.

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

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

기본 사례를 처리하기 위해 '기본'키를 추가 할 수도 있습니다.

+3

개체를 설정하는 동안 모든 단일 함수를 호출 한 다음 대체 줄에서 함수를 호출하지 않습니다. –

관련 문제