0

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.

3
  • 2
    Yes, use an object literal to store your functions.. you can then do func['modify' + defName](schema) Commented Oct 5, 2016 at 21:22
  • duh :) thanks I knew there was a way lulz Commented Oct 5, 2016 at 21:23
  • can you add it as an answer Commented Oct 5, 2016 at 21:23

3 Answers 3

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

Make the functions object properties:

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

1 Comment

window doesn't exist in node. Besides, making them global (in node) is a bad decision and unnecessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.