- Hands-On Data Structures and Algorithms with JavaScript
- Kashyap Mukkamala
- 255字
- 2021-06-30 19:12:11
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 stack. If 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)));
}
});
}
推薦閱讀
- Learn Blockchain Programming with JavaScript
- Node.js Design Patterns
- Learning Flask Framework
- 你不知道的JavaScript(中卷)
- 零基礎學Python網絡爬蟲案例實戰全流程詳解(高級進階篇)
- bbPress Complete
- UML 基礎與 Rose 建模案例(第3版)
- 深入理解Android:Wi-Fi、NFC和GPS卷
- Web前端應用開發技術
- 基于SpringBoot實現:Java分布式中間件開發入門與實戰
- Hands-On Kubernetes on Windows
- 物聯網系統架構設計與邊緣計算(原書第2版)
- SEO教程:搜索引擎優化入門與進階(第3版)
- AutoCAD基礎教程
- Learning Cocos2d-JS Game Development