Intermediate Algorithm Scripting - Arguments Optional

Tell us what’s happening:
Hi! I don’t know why my code won’t pass for addTogether(5)(7), addTogether(5) and addTogether(2)([3]).
Please help me. Thank you very much!

Your code so far

function addTogether(...num) {
  if((typeof num[0] !== 'number') | (typeof num[1] !== 'number')) return undefined;

  if(num.length === 2) return num[0] + num[1];

  return (newNum) => addTogether(newNum, num[0]);
}

addTogether(2,3);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36

Challenge: Intermediate Algorithm Scripting - Arguments Optional

Link to the challenge:

addTogether(5) should return a function.”

Explain to us what your code returns for this function call. Don’t just say “a function”. Go through your function line by line and tell us what will happen.

Also:

(typeof num[0] !== 'number') | (typeof num[1] !== 'number')

You need two pipes for a logical OR.

function addTogether(…num) {
if((typeof num[0] !== ‘number’) || (typeof num[1] !== ‘number’)) return undefined;

//This line here means if any of the provided argument is not a number, the function should return undefined.

if(num.length === 2) return num[0] + num[1];

// This line means if there isn’t any non-number argument and there are 2 arguments, which means there are 2 numbers, they return their sum

return (newNum) => addTogether(newNum, num[0]);

//This line means if the provided arguments don’t match the above 2 circumstances, which means there is only 1 number, return a function to take a new number and the new function should return the sum of the new number and the given number
}

What does this mean? I don’t think you are returning a function here.

A function and a function call are two different things.

I tried to correct it but still doesn’t work. I defined a function beforehand so this time it can surely return a function.

function addTogether() {
function func(newNum) {
    addTogether(newNum, num[0]);
  }

  if((typeof num[0] !== 'number') || (typeof num[1] !== 'number')) return undefined;

  else if(num.length === 2) return num[0] + num[1];

  else return func;
}

What does this function do?

This function takes in a new number and return the sum of this new number and the given number

Does it? How is it returning?

Not just “provided” argument(s). You are checking num[0] and num[1] no matter how many arguments are passed in. So if I call your function as:

addTogether(5)

What is going to happen when it reaches that first if statement?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.