I have a question about refactoring a function that calls other async functions depending on a variable. Currently, I am using a switch case statement and the name of the variable is the same as the name of the function. Here is an example of the current implementation:
const option = "create";
const create = async(req, res) => {
// do create stuff
}
const update = async(req, res) => {
// do update stuff
}
// etc.
switch (option) {
case "create": {
return await create(req, res);
}
case "update": {
return await update(req, res);
}
default: {
return res.status(500).json({ message: "Unable to process your request" });
}
}
Since the name of the option variable is always the same as the name of the function, I am wondering if there is a way to dynamically call the function based on the value of the option variable without the need for the switch case statement since it appears to be alot of repetition especially with the variable name and method name matching.
3
Answers
Option 1:
eval
Option 2: store references to your functions in an object.
Unlike variables, you actually can access the name of a function in Javascript:
So in theory, you could do something like this:
However, since they will always match, storing them in a hash would be cleaner/more readable code and be more performant as it doesn’t require looping through an array:
One way is to create an object of the possible values of option, and based on the values corresponding functions will be called.
Demo: