Reputation: 13
I'm currently doing the ODIN project. One of the tests is to write a function that takes two numbers and returns the sum of every number between and including them.
The function is to return the sum if both arguments are above 0. If one of the arguments is below 0 or not a number it should return 'ERROR'.
I have got it working if both arguments are integers but not for the other two parameters.
I know i've probably overcomplicated my code and there is probably a simple solution but am looking for a similar solution to mine and also a more refined version if possible.
Code is:
const sumAll = function(a, b) {
let min = Math.min(a, b)
let max = Math.max(a, b)
let range = []
let sum = 0
for (let i = min; i<= max; i++) {
range.push(i)
}
for (let j = 0; j <= range.length; j++) {
if (j < 0 || typeof j != "number") {
sum = 'ERROR'
}else
sum = sum + j
}
};
Thanks in advance
Upvotes: 1
Views: 4067
Reputation: 56
Try it:
const sumAll = function(a, b, range=[]) {
if (a < 0 || b < 0) return 'ERROR'
if (isNaN(a) || isNaN(b)) return 'ERROR'
for (let i = Math.min(a,b); i<= Math.max(a,b); i++) {
range.push(i)
}
return range.reduce((a,b) => a+b)
}
console.log(sumAll(1,10));
console.log(sumAll(10,1));
console.log(sumAll(-10,1));
console.log(sumAll(1,-10));
console.log(sumAll(1,'a'));
console.log(sumAll('a',1));
console.log(sumAll('a',-1));
Upvotes: 0
Reputation: 195
You can solve this without a for loop with simple math. The sum of a series is equal to the (end + start)(num elements)/2
. For this problem, that would be (Math.abs(a-b) + 1)(a + b)/2
.
So your answer would be:
const sumAll = function(a, b) {
if(isNaN(a) || isNaN(b)) return 'ERROR';
if(a < 0 || b < 0) return 'ERROR'
return (Math.abs(a-b) + 1)*(a + b)/2;
};
Upvotes: 1
Reputation: 31992
You can use isNaN
to check whether the parameter is a number or not. An object that is not an integer will return true
.
Your code will never return 'ERROR'
if the parameter is smaller than 0. This:
if (j < 0 || typeof j != "number") {
sum = 'ERROR'
}else
will never cause sum
to be 'ERROR'
since j
will never be smaller than 0
as its initialization value is 0
. Even if it did, you would have to add a break
, otherwise j
would be concatenated later in the for
loop (sum = sum + j
) once it no longer satisfied the condition (in the else
clause).
You also don't need the range
array at all. Just use one for
loop to iterate from min
to max
and add to sum
instead of pushing the numbers all to an array, then looping over it and adding it to sum
.
Final result:
const sumAll = function(a, b) {
if(isNaN(a) || isNaN(b)) return 'ERROR';
if(a < 0 || b < 0) return 'ERROR'
let min = Math.min(a, b)
let max = Math.max(a, b)
let sum = 0
for (let j = min; j < max; j++) //can be shortened to: for(; min < max; min++)
sum = sum + j
return sum;
};
console.log(sumAll('Hello', 'World!'));
console.log(sumAll(1, 10));
console.log(sumAll(-1, -1));
Upvotes: 0