Arguments Optional A shorter way to write this?

Arguments Optional A shorter way to write this?
0

#1

Tell us what’s happening:
Well, my code is messy and all
Is there a shorter way to write this while keeping it readable?
I tried freecodecamp advanced solution but honestly, it even more messy as it is not readable nor maintainable.

Your code so far

js

function addTogether() {
  if (typeof arguments[0] === "number" || typeof arguments[1] === "number") {
  var original = arguments[0];
  if (arguments.length === 1) {
    return function waiting(value) {
      return original + value;
    }
  } 
  if (typeof arguments[0] === "number" && typeof arguments[1] === "number") {
    return arguments[0] + arguments[1];
  }
  }
  return undefined;
}

addTogether(2,3);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional


#2

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.


#3

I also find the advanced solution unreadable. But it looks like they coded for the edge case of receiving multiple subsequent values.

I don’t know if you’ve covered higher order functions, but here’s my solution. But this only covers the tested cases.

function addTogether(...args) {
  if (!args.every(Number.isInteger)) return undefined
  if (args.length === 2) return args[0] + args[1]

  return (num) => {
    if (!Number.isInteger(num)) return undefined
    return args[0] + num
  }
}

#4

Wow, I never thought of using rest operator on the function, it seems much better to use.

I feel ashamed about my code compared to yours. However, thank you a lot!


#5

Don’t feel bad. Usually you’ll have to see a different way to do something to know that it’s even possible. I saw this trick in someone else’s code, and now you know it too :slight_smile:


#6

Thank you for making me feel better :slight_smile:


#7

Here is what i could come up with;

function addTogether() {
var arg = […arguments]
var a = arguments[0];
var b = arguments[1];

if (arg.length === 2){
while (typeof a === ‘number’ && typeof b === ‘number’){

return a + b
}

}
else if (typeof a !== ‘number’){
return undefined
}
else

return function(b) {
  if(typeof b === 'number' && typeof a === 'number')
    return a + b;
};   

}