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

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.
主站蜘蛛池模板: 泸水县| 浪卡子县| 青神县| 兴国县| 新密市| 莱州市| 城固县| 合江县| 天长市| 怀柔区| 年辖:市辖区| 潞城市| 高雄市| 黑河市| 西平县| 霍州市| 延安市| 黄浦区| 绥宁县| 汾西县| 静安区| 仪征市| 平顶山市| 彭山县| 皮山县| 岫岩| 海门市| 东丰县| 龙陵县| 庆阳市| 洛川县| 墨江| 桃园县| 雷波县| 天柱县| 水城县| 社旗县| 宁晋县| 庆城县| 张家界市| 百色市|