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

Looping Range Invalid array

In this challenge, you will build a function that creates an array for a given start, end, and step parameter.

  • The function takes three integer parameters: start, end, and step.
  • The function should return an array of numbers from start to end, counting by step.

The function checks for incorrect parameters by ensuring that;

  • start, end, or step are defined
  • start is not greater than end
  • step is greater than zero
    If any of these parameters are not met, the function should return an empty array [].

My code:

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

function range (start, end, step) {
  const result = [];
  for (let i = start; i <= end; i += step) {
    result.push(i);
  }
  return result;
}

console.log(range(0, 10, 2));

RangeError: Invalid array length

>Solution :

You forgot to do the validations described.

While doing the validations, you can use early return to get a code with more readability.

start, end, or step are defined

if (start === undefined || end === undefined || step === undefined) {
  return []
}

start is not greater than end

if (start > end) {
  return []
}

step is greater than zero

if (step <= 0) {
  return []
}

Final function:

function range (start, end, step) {
  if (start === undefined || end === undefined || step === undefined) {
    return []
  }

  if (start > end) {
    return []
  }

  if (step <= 0) {
    return []
  }

  const result = [];
  for (let i = start; i <= end; i += step) {
    result.push(i);
  }
  return result;
}
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