I'm trying to write a symbol handling calculator in JavaScript. I iterate through a list of symbols. My sample input is 1+2.
for <every element in the list> {
...
// this case handles simple numbers
var tmp = o.val;
list[pos] = {type: 'expression', val: +tmp, calc: function (x) {return +tmp} };
...
// this case handles addition
var v1 = list[pos-1].val, v2 = list[pos+1].val;
var f1 = list[pos-1].calc, f2 = list[pos+1].calc;
list[pos-1] = {type: 'expression', val: v1 + ' + ' + v2, calc: function (x) {return f1(x) + f2(x)} };
...
}
alert(list[0].val + '=' + list[0].calc(0));
The problem is that this displays 4 rather than 3. The call to calc() for the first operand doesn't return 1 anymore but 2. I wish 'calc' to hold the current values, to make a deep copy of the f1 and f2 functions. How do I achieve this? What is a good programming practice?