Currently tackling a coding challenge on Free Code Camp
The task involves receiving an array of two numbers and calculating the sum of those two numbers along with all numbers in between. The order of the numbers in the array is not fixed.
While the suggested methods to solve this include
Math.max(), Math.min(), Array.reduce()
, I decided to take a different approach initially, which led to a solution that seemed a bit cumbersome.
function sumAll(arr){
var index0 = arr[0], index1 = arr[1], counter = 0, sum = 0, val;
if(index0 < index1){
counter += index0;
while(counter <= index1){
val = index0++;
sum += val;
counter++;
}
} else if(index0 > index1){
counter = 1;
counter += index0;
while(counter >= index1){
val = index1 + 1;
sum += val;
counter--;
}
}
return sum;
}
This function works well except for cases like:
sumAll([10, 5]) //Instead of getting 45, I get 42
So my questions are:
Am I correct in thinking that my current approach is becoming too convoluted? Should I have followed the recommended methods instead? I was excited when I got my initial solution to work but now I fear I might be heading into a complex situation with potential conditions to handle.
Appreciate any insights!