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

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.
主站蜘蛛池模板: 广宁县| 富源县| 庆阳市| 宁国市| 彝良县| 金门县| 镇巴县| 德州市| 巴林右旗| 太仆寺旗| 重庆市| 纳雍县| 合肥市| 湛江市| 施甸县| 武安市| 西丰县| 康平县| 珠海市| 长汀县| 泰宁县| 龙泉市| 建阳市| 新巴尔虎右旗| 娄底市| 麟游县| 红桥区| 台东县| 乐东| 米泉市| 海原县| 从化市| 宁安市| 新宾| 怀集县| 额尔古纳市| 盘山县| 元朗区| 改则县| 招远市| 鄂伦春自治旗|