官术网_书友最值得收藏!

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)));
}
});
}
主站蜘蛛池模板: 九龙城区| 德州市| 牙克石市| 固始县| 汝阳县| 罗田县| 天门市| 朝阳县| 廊坊市| 玛曲县| 定边县| 东丽区| 岚皋县| 卫辉市| 中江县| 丰都县| 临城县| 玉溪市| 锡林郭勒盟| 乌拉特中旗| 合作市| 阳谷县| 合作市| 凤台县| 防城港市| 嘉荫县| 贵州省| 台中市| 介休市| 洪泽县| 东源县| 宁陵县| 库尔勒市| 嘉荫县| 太和县| 会东县| 酉阳| 赣州市| 象州县| 西藏| 前郭尔|