Intermediate Algorithm Scripting - Arguments Optional

Tell us what’s happening:

Hi,

I can get my code to pass all the cases apart from the one where the two arguments are passed somewhat differently. There must be a technical term for it, but it’s not something that I recall having learned yet.

e.g. when a function is called like funct(a)(b) rather than funct(a, b)

I’ve tweaked around with my code, but I can’t see what I’d need to do to be able to get it to accept such calls. Unless it’s not possible with the way I’ve written the code. I’ve written the start of the code like that just to be able to deal with cases where the input is greater than 2 arguments and the user has to be informed that they should only supply one or two. I know the challenge doesn’t ask for that, but I think it’s good practice.

Thanks in advance.

Anthony.

Your code so far

function addTogether(...args) {
  for (let i = 0; i < args.length; i++) {
    if ((typeof args[i] === 'number') && i == (args.length - 1)) {
      break;
    } else if (typeof args[i] === 'number') {
      continue;
    } else {
      return undefined;
    }
  }

  if (args.length == 1) {
    return num => addTogether(args + num);
  } else if (args.length == 2) {
    return args[0] + args[1];
  } else {
    return undefined;
  }
  
}

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/119.0.0.0 Safari/537.36

Challenge Information:

Intermediate Algorithm Scripting - Arguments Optional

What type of value is args?

Thanks for your reply, Colin.

Args is a number. I’m not sure I understand your question. If the args passed are not numbers, I’m returning undefined.

I’ve managed to get it to work by adding a [0] after args. I had put a plus sign as well, accidently, which I’ve corrected, but it appears to have been that I needed to write args[0], rather than just args. I didn’t think it would matter because that’s covering cases where only one argument is passed…

  for (let i = 0; i < args.length; i++) {
    if ((typeof args[i] === 'number') && i == (args.length - 1)) {
      break;
    } else if (typeof args[i] === 'number') {
      continue;
    } else {
      return undefined;
    }
  }

  if (args.length == 1) {
    return (num) => addTogether(args[0], num);
  } else if (args.length == 2) {
    return args[0] + args[1];
  } else {
    return undefined;
  }
  


}

addTogether(2, 3);
type or paste code here

How are you sure that args is a number? Go ahead and try logging it to the console to check.

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