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