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

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:4200Now, 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:

  1. Converting input expression to a machine-understandable expression.
  2. Evaluating the postfix expression.
  3. Returning the expression's value to the parent component.
主站蜘蛛池模板: 敦煌市| 慈利县| 平潭县| 寿光市| 利辛县| 龙川县| 临夏市| 南开区| 马尔康县| 蓬安县| 萍乡市| 仪征市| 西贡区| 获嘉县| 大邑县| 东安县| 福海县| 沛县| 岢岚县| 万安县| 江油市| 西畴县| 开平市| 即墨市| 临邑县| 山丹县| 灵宝市| 静宁县| 永川市| 吉木乃县| 青铜峡市| 大名县| 阿合奇县| 金华市| 靖安县| 滨州市| 徐汇区| 凌源市| 广宗县| 石楼县| 富蕴县|