- Hands-On Data Structures and Algorithms with JavaScript
- Kashyap Mukkamala
- 252字
- 2021-06-30 19:12:11
Enabling web worker communications
Now that the app component is set and ready to send messages, the worker needs to be enabled to receive the messages from the main thread. To do that, add the following code to your worker.js file:
init();
function init() {
self.addEventListener('message', function(e) {
var code = e.data;
if(typeof code !== 'string' || code.match(/.*[a-zA-Z]+.*/g)) {
respond('Error! Cannot evaluate complex expressions yet. Please try
again later');
} else {
respond(evaluate(convert(code)));
}
});
}
As you can see, we added the capability of listening for any message that might be sent to the worker and then the worker simply takes that data and applies some basic validation on it before trying to evaluate and return any value for the expression. In our validation, we simply rejected any characters that are alphabetic because we want our users to only provide valid numbers and operators.
Now, start your application using the following command:
npm start
You should see the app come up at localhost:4200. Now, simply enter any code to test your application; for example, enter the following:
var a = 100;
You would see the following error pop up on the screen:

Now, let's get a detailed understanding of the algorithm that is in play. The algorithm will be split into two parts: parsing and evaluation. A step-by-step breakdown of the algorithm would be as follows:
- Converting input expression to a machine-understandable expression.
- Evaluating the postfix expression.
- Returning the expression's value to the parent component.
- PHP動態網站程序設計
- Advanced Quantitative Finance with C++
- 深度實踐OpenStack:基于Python的OpenStack組件開發
- CMDB分步構建指南
- Boost C++ Application Development Cookbook(Second Edition)
- 技術領導力:程序員如何才能帶團隊
- Extending Puppet(Second Edition)
- NGINX Cookbook
- Scala編程(第5版)
- 編程改變生活:用Python提升你的能力(進階篇·微課視頻版)
- 青少年學Python(第2冊)
- Selenium WebDriver Practical Guide
- 美麗洞察力:從化妝品行業看顧客需求洞察
- Python全棧開發:數據分析
- Java程序性能優化實戰