Home > Article > Web Front-end > Code implementation of JavaScript arithmetic expression calculator
The first step is to implement the createOperator function and return the closure function:
var Add = createOperator("+" , function(a,b){return a + b;}); var Minus = createOperator("-" , function(a,b){return a - b;}); var Mul = createOperator("*" , function(a,b){return a * b;}); var pide = createOperator("/" , function(a,b){return a / b;});
1. An instance of the closure function has two eval and toString Method
2. The eval method is responsible for calculating the value of the arithmetic expression
3. The toString method uses the string form to calculate the expression Display
4. The scope of application is limited to binary Operator
var a = new Add(new Value(3), new Value(5)); //8 console.log(a.eval()); //"3 + 5" console.log(a.toString()); var b = new Mul(new Value(6), new Value(2)); //12 console.log(b.eval()); //"6 * 2" console.log(b.toString()); var c = new Add(a,b); //20 console.log(c.eval()); //"3 + 5 + 6 * 2" console.log(c.toString());
The values during the operation are stored in the form of Value
function Value(value){ this.value = value || 0; } Value.prototype.toString = function(){ return this.value.toString(); };
createOperator function Code implementation:
//IIFE var createOperator = (function() { //name:"+","-","*","/" //oper:对应的加减乘除函数 return function(name, oper){ //闭包函数 var Foo = function(){ //获取2个操作数 var args = arguments; var nums = [].slice.call(arguments); nums = nums.map(function(e){return e.value;}); var val = new Value(oper.apply(null,nums)); //给实例绑定toString和eval方法 val.toString = function(){ return args[0].toString() + " " + name + " " + args[1].toString(); }; val.eval = function(){ return this.value; }; return val; }; return Foo; }; })();
The above is the detailed content of Code implementation of JavaScript arithmetic expression calculator. For more information, please follow other related articles on the PHP Chinese website!