Use variable value to compose function calling command

Asked

Viewed 24 times

1

When I begin to abstract in various functions my systems, this doubt almost always appears to me. I have the value "local" in the variable sPrg, and I need to concatenate with "Ctrl.save" to call the function.

How can I reduce this so I don’t need to use the switch?

ctrl.gravar = function (sPrg) {
   switch(sPrg){
      case "local":
         localCtrl.gravar();
         break;
      case "banco":
         bancoCtrl.gravar();
         break;
      case "cartao":
         cartaoCtrl.gravar();
         break;
      case "saldo":
         saldoCtrl.gravar();
         break;
   }
};

1 answer

2


Quick response

Ctrl types (hence switch options) could be attributes of an object:

// no plural
const ctrls = {
  local: localCtrl,
  banco: bancoCtrl,
  cartao: cartaoCtrl,
  saldo: saldoCtrl
};

ctrl.gravar = function(sPrg) {
    ctrls[sPrg].gravar();
}

Bonus

Using the beautiful syntax of Arrow functions:

ctrl.gravar = sPrg => ctrls[sPrg].gravar();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.