So I am trying to answer this exercise from Eloquent Javascript Chapter 4 (The sum of a range) (check the bottom of the page).
My problem is I am getting "Uncaught out of memory" error when running certain combinations like for the example I pasted here.
I don’t see anything wrong with the code. If I changed the range call to a start/end from 35, 30, -1 to, for example, 30, 35, 2 I would get a result so I am confused.
Appreciate any help.
https://eloquentjavascript.net/04_data.html
let all = [];
function range (start, end, step = 1) {
if (start < end) {
for (let i = start; i <= end; i += step)
all.push(i);
}
else if (start > end) {
for (let i = start; i >= end; i -= step)
all.push(i);
}
else
throw new Error
("Start is equal to End or something else went wrong! Check your input");
return all;
}
range(35, 30, -1);
console.log(all);
>Solution :
Using arguments (35, 30, -1) the 2nd for loop will trigger.
With values substituted that reads:
for (let i = 35; i >= 30; i -= (-1))
all.push(i);
You made the step argument negative, but are also decreasing by that value, which in effect means you are adding 1 to i. In that case the loop end condition is never reached (i goes from 35 towards +infinity, i >= 30 never becomes false), leading to an array overflow.
You probably want to limit step to values of 1 and higher, and let the for loop decide if it does += or -= with that value.