Problems encountered
Recently in the development of small programs, the code needs to achieve a lot of business, it is inevitable to have a lot of judgment, according to different strategies to run different functions exist. Get the string and execute the corresponding function.
In PHP, you can do this easily
$con = 'hello';
$con(); // hello()
$con = 'king';
$con(); // king()
Copy the code
Eval is evil. Eval is evil. Eval is evil. Efficiency is not good and unsafe, decisively gave up.
What should I do?
A, If the Else
if(con) {
// do something
}else if(con){
// do something}... else{// do something
}
Copy the code
Too much if else doesn’t look good either
Second, the switch case
Switch case will be better, but still infinite copy code, very uncomfortable:
switch(mf.queue[key]) {
case 'login':
// do something
break;
case 'chat':
// do something
break; . default:// do something
}
Copy the code
For simple string conversions, you can also consider using enumerations.
The solution
// Business logic
const funA = function(arg){
// do something
}
const funB = function(arg){
// do something}...// Map
const actions = new Map([['funA',funA],
['funB',funB] ...... ] )const choose = function(arg){
var fun = 'funA'
actions.get(fun)(arg) // funA(arg)
actions.get('funB')(arg) // funB(arg)
}
// Method of exposure
module.exports = {
choose:choose,
}
Copy the code
conclusion
This is a little bit more mechanical than the infinite copy if else, and it’s a little bit more of an alternative to eval.