I’m trying to implement a primitive type of Polish Notation Calculator and I’m using an object to define each operation.
Such that calling
new RPNCalculator().calculate([4, 5, '+']);
will produce an answer of 9 or
new RPNCalculator().calculate([4, 5, '+', 3, 5, '+', '*']);
will produce an answer of 72.
The code is here:
function RPNCalculator(arr) {
this.calculate = function(arr) {
var resultArr =[];
for(var i=0; i < arr.length; i++) {
if(typeof(arr[i]) == 'number') {
resultArr.push(arr[i]);
}
else {
var a = resultArr.pop();
var b = resultArr.pop();
var c = opers[arr[i]].apply(this, [a, b]);
resultArr.push(c);
}
}
return resultArr.pop();
}
var opers = {
"+": function(a, b) { return a + b; },
"-": function(a, b) { return a - b; },
"*": function(a, b) { return a * b; },
"/": function(a, b) { return a / b; }
}
}
The calculations work correctly, but what I would like to know is whether the following line
var c = opers[arr[i]].apply(this, [a, b]);
is the best way to invoke the required function contained inside the opers object based on the symbol at the current index in the array, or is there a better way to do it?
You don’t really need a reference to
thisin your code, because the functions aren’t working on any class members.In this case, you can simply do:
Which is a little cleaner. To be the most readable, however, I recommend this: