sai5i
1
function addTogether() {
let args = Array.from(arguments)
return args.some(n => typeof n !== "number")
? undefined
: args.length > 1
? args.reduce((acc, n) => (acc += n), 0)
: n => (typeof n === "number" ? n + args[0] : undefined);
}
addTogether(2);
Would someone please help me understand how the above solution works to return a function if one argument is passed to addTogether function. thanks
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0.
Challenge: Arguments Optional
Link to the challenge:
This is definitely not the easiest code to read. The function is being returned here:
: n => (typeof n === "number" ? n + args[0] : undefined)
This is an anonymous arrow function that takes one argument (n).
The easiest way to read the return statement is to think of it as a bunch of if/else statements:
if (args.some(n => typeof n !== "number") === true) {
return undefined;
}
else if (args.length > 1) {
return args.reduce((acc, n) => (acc += n), 0);
}
else {
return n => (typeof n === "number" ? n + args[0] : undefined);
}
sai5i
3
Very well explained and I recalled the anonymous function now
thanks a lot