Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Memory overflow can't figure it out

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading