Created
February 21, 2019 00:07
-
-
Save JeffOgah/962acb678269929f8376c0401997c89b to your computer and use it in GitHub Desktop.
JavaScript Intermediate Algorithm Scripting: Arguments Optional
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /*Create a function that sums two arguments together. If only one argument is provided, | |
| then return a function that expects one argument and returns the sum. | |
| For example, addTogether(2, 3) should return 5, and addTogether(2) should return a function. | |
| */ | |
| function addTogether() { | |
| let firstNum, secondNum; //numbers to be added | |
| //function to check if argument is a number | |
| function validNumber(num) { | |
| if (typeof num == 'number') | |
| { | |
| return num; | |
| } | |
| return undefined; | |
| } | |
| //if 2 or more arguments are passed | |
| //check first two arguments, sum if both are numbers else return undefined | |
| if (arguments.length >1) { | |
| firstNum = validNumber(arguments[0]); | |
| secondNum = validNumber(arguments[1]); | |
| return (firstNum && secondNum ? firstNum + secondNum : undefined); | |
| } | |
| else { | |
| firstNum = validNumber(arguments[0]); | |
| //check if any undefined number was passed, return function to accept | |
| //return a function to accept and check second number if present then sum | |
| if (firstNum !== undefined) { | |
| return function secondNumber(arg){ | |
| secondNum = validNumber(arg); | |
| if (firstNum === undefined || secondNum === undefined ) { | |
| return undefined; | |
| } | |
| else {return firstNum + secondNum;} | |
| } | |
| } | |
| } | |
| } | |
| addTogether(2,3); //returns 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment