Detailed explanation of the sample code of the JavaScript chained call Calculator

Source: Internet
Author: User
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.