Evaluating postfix expressions

From here on, executing this postfix notation is fairly easy. The algorithm is relatively straightforward; you pop out each of the operators onto a final result stackIf the operator is one of *, ^, +, -, /, then evaluate it accordingly; otherwise, keep appending it to the output string:

function evaluate(postfix) {
var resultStack = new Stack();
postfix = clean(postfix.trim().split(" "));
postfix.forEach(function (op) {
if(!isNaN(parseFloat(op))) {
resultStack.push(op);
} else {
var val1 = resultStack.pop();
var val2 = resultStack.pop();
var parseMethodA = getParseMethod(val1);
var parseMethodB = getParseMethod(val2);

if
(op === "+") {
resultStack.push(parseMethodA(val1) + parseMethodB(val2));
} else if(op === "-") {
resultStack.push(parseMethodB(val2) - parseMethodA(val1));
} else if(op === "*") {
resultStack.push(parseMethodA(val1) * parseMethodB(val2));
} else if(op === "/") {
resultStack.push(parseMethodB(val2) / parseMethodA(val1));
} else if(op === "^") {
resultStack.push(Math.pow(parseMethodB(val2),
parseMethodA(val1)));
}
}
});

if (resultStack.size() > 1) {
return "error";
} else {
return resultStack.pop();
}
}

Here, we use some helper methods such as getParseMethod() to determine whether we are dealing with an integer or float so that we do not round any number unnecessarily.

Now, all we need to do is to instruct our worker to return the data result that it has just calculated. This is done in the same way as the error message that we return, so our init() method changes as follows: 

function init() {
self.addEventListener('message', function(e) {
var code = e.data;

if(code.match(/.*[a-zA-Z]+.*/g)) {
respond('Error! Cannot evaluate complex expressions yet. Please try
again later'
);
} else {
respond(evaluate(convert(code)));
}
});
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.135.125