2

function(response) {
  if (response.bMap && SelType === 'q') {
    setDefaultQQ(response.bMap);
  } else if (response.bMap && SelType === 'a') {
    setDefaultAA(response.bMap);
  } else if (response.bMap && SelType === 'o') {
    setDefaultOO(response.bMap);
  } else if (response.mMap && SelType === 'm') {
    setDefaultMM(response.mMap);
  } else if (response.bMap && SelType === 'p') {
    setDefaultPP(response.bMap);
  } else if (response.eMap && SelType === 'e') {
    setDefaultEE(response.eMap);
  } else {
    setDefaultData();
    showModal();
  }
}

Is there a way to reduce this conditional statement into shorter form and better readability

jsduniya
  • 2,464
  • 7
  • 30
  • 45
  • Not exactly related, but this questions seems to conflict with your profile just a bit ; ). – Teemu Feb 08 '17 at 12:40

2 Answers2

2

Could use an object to map the SelType specific methods

var methods = {
  'a': setDefaultQQ,
  'o': setDefaultOO,
  'm': setDefaultMM,
  ....    
}

if(response.bMap && methods[SelType]){
   methods[SelType](response.bMap);
}else{
   setDefaultData();
   showModal();
}
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • you are missing my other keys eMap and Mmap – jsduniya Feb 08 '17 at 12:48
  • so you will need additional logic. My guess is you could have used one method and pass in response object as argument and do everything there – charlietfl Feb 08 '17 at 12:51
  • Yes I was adding additional logic, but this is the method, where i am passing my response param, Do you mean to add me another method to seperate the logic ? – jsduniya Feb 08 '17 at 12:54
0

There is not really a good way but how about this

eval("setDefault"+SelType.toUpperCase()+SelType.toUpperCase()+"(response."+SelType.toUpperCase()+"Map);");

But certainly not the best way.

kawadhiya21
  • 2,458
  • 21
  • 34
  • It's interesting to see that this could be done this way but please don't use `eval()` unless you really have to (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/eval#Don't_use_eval_needlessly!). You own code and @charlietfl's answer proves that it is not necessary :) – atwright147 Feb 08 '17 at 12:49
  • I wanted to make it dynamic. If someday you add another `SelType`, you won't have to come back and update `SelType` key to function mapping etc. – kawadhiya21 Feb 08 '17 at 12:55
  • kawadhiya21 that makes sense, but still i am not allowed to use eval here.. – jsduniya Feb 08 '17 at 15:41