Arguments Optional-freecodecamp Algorithm Topics

Source: Internet
Author: User

Arguments Optional

1. Requirements

    • Create a function that calculates the sum of two parameters. If there is only one argument, a function is returned, and the function requests a parameter and then returns the result of the sum.
    • If none of the two parameters is a valid number, the undefined is returned.

2. Ideas

    • Determine the number of input data
    • The number of data is 1, the data type is judged,
      • Type is a number: Assign this data to a, return a function, this function requires a data B, judge the type of B, is the number returned A+B, not the number, return undefined;
      • Type is not a number: returns undefined.
    • The number of data is 2, the data type is judged, both are numeric, return two data and, otherwise, return undefined.

3. Code

function add() {  if(arguments.length===1){      if(typeof(arguments[0])==='number'){        var a=arguments[0];          return function(b){            if(typeof(b)==='number'){              return a+b;            }            else{              return undefined;            }          };      }      else{        return undefined;      }  }  else if(arguments.length===2){    if(typeof(arguments[0])==='number' && typeof(arguments[1])==='number'){      return arguments[0]+arguments[1];    }    else{      return undefined;    }  }}add(2)(2);

4. RELATED LINKS

    • Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/arguments
    • Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Closures

Arguments Optional-freecodecamp Algorithm Topics

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.