for example, suppose I need to do different things according to combinations of boolean values: cond_0,cond_1 and cond_2 :
cond_0 cond_1 cond_2
false false false a();
false false true b();
.
.
.
true true true h();
it looks as if mapping bit numbers to functions:
000:a()
001:b()
.
.
.
111:h()
while the general rule looks like very simple, I don't know how to write it without if-else, and the current form looks like that:
var f=function(cond_0,cond_1,cond_2){
if(!cond_0 && !cond_1 && !cond_2){
a();
}else if( cond_0 && !cond_1 && !cond_2)){
b();
}else if(!cond_0 && cond_1 && !cond_2)){
c();
}else if( cond_0 && cond_1 && !cond_2)){
d();
}else if(!cond_0 && !cond_1 && cond_2)){
e();
}else if( cond_0 && !cond_1 && cond_2)){
f();
}else if(!cond_0 && cond_1 && cond_2)){
g();
}else if( cond_0 && cond_1 && cond_2)){
h();
}
}
which is very long and hard to read. And when a new boolean condition cond_3 is added, it is horrible to modify the code:
if(!cond_0 && !cond_1 && !cond_2 && !cond_3){
a();
}else if( cond_0 && !cond_1 && !cond_2 !cond_3)){
b();
}
.
.
.
Is there any way to eliminate the if else, so that cond_0 , cond_1 and cond_2 can just appear once only inside the function, and also easy to add new function when cond_3 is added? I want something like:
var f=function(cond_0,cond_1,cond_2){
var magic=(000:a,001:b,010:c...);
magic(cond_0,cond_1,cond_2)();
}
Aucun commentaire:
Enregistrer un commentaire