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));
CodePudding user response:
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.
CodePudding user response:
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));