I am trying to replace some mathematical operators with variables, so that I can change the operator according to some conditions and then an then use that variable in place of the operator.
For example
var abc = 5;
if (abc<5)
// perform subtraction;
else if(abc==5)
// perform addition;
else if(abc>5)
// perform multiplication
Now what I want is that instead performing the operations based on the value of variable abc
assign the operator it self to some variable and then use the variable in place of the operator, so that I can reduce some code and only one block of code can be used in place of 3 or 5 blocks.
Something like this
var sign;
var result;
if(some condition)
sign = "-";
result = 5 sign 4;
I want to do this mainly in javascript.
You can use
evalfor this specific case:This will perform “dynanic operation” on two numbers (10 and 10 in this example) based on the value of
abcby storing the operator as a string then evaluate it.Live test case.