LazioTibijczyk
LazioTibijczyk

Reputation: 1937

How to avoid use of eval to call different functions

I have this bit of code that include eval because I found it the easiest to call different factory functions which make different web service calls.

I have read it's not safe and 'appropriate' way of doing it. Well, I can't think or find a better way to suit my need.

How can I possibly improve the call?

vm.saveRecord = function() {
    var service = '';

    if(vm.valueTrue) {
        service = vm.otherValue ? 'function1' : 'function2';
    } else {
        service = vm.otherValue ? 'function3' : 'function4';
    }

    eval(service).callEndPoint(param1, param2).then(
        function successCallback(response) {
            if(response) {
                //successful response
            }
        }, function errorCallback(response) {
            //error
        }
    )
};

Upvotes: 0

Views: 45

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386654

You could take either the functions directly

vm.saveRecord = function() {
    var service = vm.valueTrue
            ? vm.otherValue
                ? function1
                : function2
            : vm.otherValue
                ? function3
                : function4;

    service.callEndPoint(param1, param2).then(
        function successCallback(response) {
            if(response) {
                //successful response
            }
        }, function errorCallback(response) {
            //error
        }
    )
};

or move the functions into an object where the key is the accessor.

vm.saveRecord = function() {
    var services = { function1, function2, function3, function4 },
        service = vm.valueTrue
            ? vm.otherValue
                ? 'function1'
                : 'function2'
            : vm.otherValue
                ? 'function3'
                : 'function4';

    services[service].callEndPoint(param1, param2).then(
        function successCallback(response) {
            if(response) {
                //successful response
            }
        }, function errorCallback(response) {
            //error
        }
    )
};

Upvotes: 2

VLAZ
VLAZ

Reputation: 29047

You can use the function handle to execute a function. This would be the reference to the function:

//existing functions
function one() {   console.log("one")   };
function two() {   console.log("two")   };
function three() { console.log("three") };

//function that will execute other functions
function exec(number) {
  //we will assign a function here
  let toExecute;
  
  //simple condition to choose the function to execute at the end
  if (number == 1) {
    toExecute = one;
  } else if (number == 2) {
    toExecute = two;
  } else if (number == 3) {
    toExecute = three;
  }
  
  //adding () executes whatever function is assigned to the variable
  toExecute();
}


exec(3);
exec(2);
exec(1);

Upvotes: 2

Related Questions