this question has answer here:
hi i'm making string calculator , add. i'm using coffeescript , in code provided finalnum 0, operator '+' , it's iterating through array of integers. plan on adding more operators later , looking simpler way (not massive if else) change string it's corresponding operator. help!
for num in equation_array finalnum = finalnum operator num
the simplest way abstract using functions instead of trying abstract on operator directly.
var ops = { '+': function(a,b){ return + b; }, '-': function(a,b){ return - b; }, '*': function(a,b){ return * b; }, '/': function(a,b){ return / b; } }; var opstr = "+"; final_num = ops[opstr](final_num, num);
Comments
Post a Comment