Use JavaScript to implement a simple chain call calculator, and use the new features of ECMAScript5 and 6. A typical chained syntax calculator is used like this:
FluentCalculator.one.plus.two // 1 + 2 = 3FluentCalculator.one.plus.two.plus.three.minus.one.minus.two.minus.four // -1FluentCalculator.one.plus.ten - 10 // 1 + 10 - 10 = 1
If an exception is called, undefined is returned:
FluentCalculator. one. one // undefined. Because the value cannot be called, FluentCalculator. one. plus. plus // undefined cannot be called consecutively.
To solve this problem, we have to determine the concept that stateful transmission is passed between calls, and there are two statuses.
When the value (num) Call ends, the operation status object (OprStatus) is returned ).
When an operation (opr) Call ends, a value State object (NumStatus) is returned ).
That is to say, the two States are alternating. If there is no alternating state, it is called abnormally and undefined is returned.
"Use strict"; var num = ["zero", "one", "two", "three", "four", "five", "six ", "seven", "eight", "nine", "ten"]; var oprs = {plus: "+", minus: "-", times :"*", pidedBy: "/"}; var Magic = {}; // Status object, parent object function Status (value, opr) {// current operation result this. value = value; // The current operator this. opr = opr;} // value Status object, inheriting the Status object function NumStatus (value, opr) {Status. call (this, value, opr);} // operation Status object, inheriting the State object function OprStatus (value, opr) {Status. call (this, value, opr);} // bind the method for (let I = 0; I
The above is a detailed description of the sample code of the JavaScript chained call calculator. For more information, see other related articles in the first PHP community!