Alexander Mills
Alexander Mills

Reputation: 100070

Avoid using eval() to call function by name with only dynamic string

I have this simple switch block:

function modifyServiceContractView(schema) {
     ...
}

function modifyContactView(schema) {
    ...
}


function addExtraInfoToSchema(defName, schema) {

  switch (defName) {

    case 'ServiceContractView':
      return modifyServiceContractView(schema);
      break;

    case 'ContactView':
      return modifyContactView(schema);
      break;

    default:
      return schema;

  }

}

instead of hardcoding a switch block, it would be nice to just have something like this instead:

function modifyServiceContractView(schema) {
    ...
}

function modifyContactView(schema) {
    ...
}


function addExtraInfoToSchema(defName, schema) {

    return eval('modify' + defName+ '(schema)');

}

is there a better way to do this without eval()?

hopefully my question is clear.

Upvotes: 0

Views: 501

Answers (3)

trincot
trincot

Reputation: 350310

Make the functions object properties:

return (f => f ? f(schema) : schema)({
    modifyServiceContractView,
    modifyContactView
}['modify' + defName]);

Upvotes: 0

Mike Cluck
Mike Cluck

Reputation: 32511

You could store your functions in an object then access them by name.

var modify = {
  ServiceContractView: function(schema) {
    console.log('ServiceContract', schema);
  },
  ContactView: function(schema) {
    console.log('Contact', schema);
  }
};

function addExtraInfoToSchema(defName, schema) {
  return modify[defName](schema);
}

addExtraInfoToSchema('ServiceContractView', 1);
addExtraInfoToSchema('ContactView', 2);

Upvotes: 1

Barmar
Barmar

Reputation: 781096

Use an object whose keys are the names and values are the functions.

var modifyFuncs = {
    ServiceContractView: modifyServiceContractView,
    ContactView: modifyContactView
};

function addExtraInfoToSchema(defName, schema) {
    if (defName in modifyFuncs) {
        return modifyFuncs[defName](schema);
    } else {
        return schema;
    }
}

Upvotes: 1

Related Questions