0

I want my code to return error if one of the parameter is negative How do that.

const sumAll = function(num1,num2) {
    let newArr = [num1,num2];
    let sortedArr = newArr.sort(function(a,b) {
        return a - b;
    })
    let lastArr = []
    for (let i = sortedArr[0]; i <= sortedArr[1]; ++i ) {
        lastArr.push(i)
    }
    let reducedArr = lastArr.reduce(function(previousValue,currentValue) {
        return previousValue + currentValue;
    })
    return reducedArr;
};

console.log(sumAll(1,-4));
Andy
  • 61,948
  • 13
  • 68
  • 95
I.blue
  • 17
  • 7

2 Answers2

1

Try something like this

const sumAll = function(num1,num2) {
    if (num1 < 0 || num2 < 0) {
        throw "Num1 and num2 must not be negative"
    }
    let newArr = [num1,num2];
    let sortedArr = newArr.sort(function(a,b) {
        return a - b;
    })
    let lastArr = []
    for (let i = sortedArr[0]; i <= sortedArr[1]; ++i ) {
        lastArr.push(i)
    }
    let reducedArr = lastArr.reduce(function(previousValue,currentValue) {
        return previousValue + currentValue;
    })
    return reducedArr;
};

console.log(sumAll(1,-4));

If you want to return an error message instead of throwing an error, replace the word throw with the word return on line 3.

Peter
  • 61
  • 4
-1

If question is related to negative parameter check, I think you can use Math.sign() function for checking negativity/positivity of values.

Math.sign(-4) returns -1

Math.sign(4) returns 1

In if case it will be represents true/false

const sumAll = function(num1,num2) {
  if (Math.sign(num1) || Math.sign(num2)) {
    return "Parameters must be positive integer."
  }

  let newArr = [num1,num2];
  let sortedArr = newArr.sort(function(a,b) {
    return a - b;
  });

  let lastArr = [];

  for (let i = sortedArr[0]; i <= sortedArr[1]; ++i ) {
    lastArr.push(i);
  }

  let reducedArr = lastArr.reduce(function(previousValue,currentValue) {
    return previousValue + currentValue;
  });

  return reducedArr;
 };
    
console.log(sumAll(1,-4));
Batuhan
  • 1,521
  • 12
  • 29
  • Your checks are wrong, `-1` is also a truthy value. You need to explicitly check for `< 0` – UnholySheep Oct 01 '21 at 23:09
  • I don't think so if param value equals `-0` your explicit check will failed. You can test it `-0 < 0` returns `false`. @UnholySheep – Batuhan Oct 01 '21 at 23:12
  • It is not wrong, question includes many open edges. This is one of them. @UnholySheep – Batuhan Oct 01 '21 at 23:16