Intermediate Algorithm Scripting - Arguments Optional

Hello everyone,

I have written the code below but it fails the double argument tests and I can’t work out why. According to the console.logs both inside and outside the function, the correct answers are there but the tests still fail. Is it a problem with scope? Any help or advice would be much appreciated.

let total = 0;
let i = 0;

function addTogether(...arg) {
  i++;

console.log(arg[0]);
console.log(arg.length);
console.log(typeof arg[0]);
console.log(total);
console.log(i)

  if (arg.length === 2) {
    if (typeof arg[0] != 'number' || typeof arg[1] != 'number') {
      return undefined;
    } else {
      return arg[0] + arg[1];
    }
  }
  
  if (arg.length === 1) {
    if (typeof arg[0] != 'number') {
      return undefined;
    }
    total += arg[0];

console.log(total)

    if (i === 1) {
      return addTogether;
    } else if (i === 2) {
      return total;
    }
  }
}

addTogether(5)(7);
console.log(total)

I would definitely rework this so that it doesn’t use global variables.

1 Like
  1. Try use local variables to solve them.
  2. After that , check again the logic & function you returning for addTogether(5)(7), because it seems that your if-else misunderstood this

addTogether(5)(7)

as:

addTogether(5)

image

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