2

Hi i'm making a String Calculator and all it currently does is add. I'm using coffeescript and in the code provided finalnum is 0, operator is '+' and it's iterating through an array of integers. I plan on adding more operators later and am looking for a simpler way (not a massive if else) to quickly change a string to it's corresponding operator. Thanks for your help!

for num in equation_array
    finalnum = finalnum operator num
Tom McGee
  • 136
  • 6
  • http://stackoverflow.com/questions/13077923/how-can-i-convert-a-string-into-a-math-operator-in-javascript – loli Jul 17 '15 at 16:19

1 Answers1

2

The simplest way is to abstract using functions instead of trying to abstract over the operator directly.

var ops = {
  '+': function(a,b){ return a + b; },
  '-': function(a,b){ return a - b; },
  '*': function(a,b){ return a * b; },
  '/': function(a,b){ return a / b; }
};

var opstr = "+";
final_num = ops[opstr](final_num, num);
hugomg
  • 68,213
  • 24
  • 160
  • 246