Evil Eval, strategy pattern to the resque
A dreadful and utterly painful attempt to create an interchangeable operator.
var op = "";
if (abc>5)
op = "-";
else if(abc==5)
op = "+";
else
op = "*";
if (op.length > 0)
alert(eval("10" + op + "10"));
- Inconsistent white space
- No brackets
- eval !!
My suggestion, use a strategy pattern.
function multiply(a, b) {
return a * b;
}
function substract(a, b) {
return a - b;
}
function add(a, b) {
return a + b;
}
var sign, result, abc = 10;
if( abc < 5 ) {
sign = substract;
}else if( abc == 5 ) {
sign = add;
}else if( abc > 5 ) {
sign = multiply;
}
result = sign(5, 4);
Read the story here http://stackoverflow.com/a/9989085/1173062