Arguments Optional
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.
addTogether(2, 3)
should return 5.
Passed
addTogether(23, 30)
should return 53.
Passed
addTogether(5)(7)
should return 12.
Passed
addTogether("http://bit.ly/IqT6zt")
should return undefined
.
Passed
addTogether(2, "3")
should return undefined
.
Passed
addTogether(2)([3])
should return undefined
.
freeCodeCamp Challenge Guide: Arguments Optional
function addTogether() {
let args = Array.prototype.slice.call(arguments, 0)
let a = args[0]
if (typeof a !== "number") return;
if (arguments.length === 1) {
return function () {
let b = Array.prototype.slice.call(arguments, 0)[0]
if (typeof b !== "number") return;
return +a + + b
}
}
let b = args[1]
if (typeof b !== "number") return;
return Array.prototype.reduce.call(arguments, (x, y) => +x + +y)
}
console.log(
addTogether(2)(3)
)