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

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)));
}
});
}
主站蜘蛛池模板: 邵阳县| 元谋县| 红桥区| 青河县| 乾安县| 汤阴县| 大足县| 安庆市| 玉山县| 松滋市| 临朐县| 嵊州市| 芦溪县| 德阳市| 上栗县| 格尔木市| 河东区| 新津县| 宁波市| 浦城县| 岢岚县| 尚义县| 湛江市| 岳阳县| 马边| 库车县| 四子王旗| 安国市| 四子王旗| 无为县| 桃源县| 噶尔县| 翼城县| 洛宁县| 汉源县| 巴彦淖尔市| 泰来县| 年辖:市辖区| 内江市| 湟中县| 阿荣旗|