Created
September 6, 2020 12:53
-
-
Save zenius/3080ed1d10c2a2e0a3ad2aae845a5347 to your computer and use it in GitHub Desktop.
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. | |
Calling this returned function with a single argument will then return the sum: | |
var sumTwoAnd = addTogether(2); | |
sumTwoAnd(3) returns 5. | |
If either argument isn't a valid number, return undefined. | |
Solution: | |
function addTogether(...args) { | |
const length = args.length; | |
if(length === 1) { | |
if(typeof args[0] !== "number") { | |
return undefined; | |
} | |
return function(y) { | |
if(typeof y !== "number") { | |
return undefined; | |
} | |
return args[0] + y; | |
} | |
} | |
if(typeof args[1] !== "number") { | |
return undefined; | |
} | |
return args[0] + args[1]; | |
} | |
addTogether(2,3); | |
Link: | |
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment