Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

130
Vistas
Trying to make a function that prints an array range. I'm given the start, stop and step values. I keep getting an infinite loop

I am trying to write a function that returns a list of integers from a 'start' value (inclusive) to a 'stop' value (exclusive) and am given the 'step' (or number to increment by...).

The function is supposed to be able to handle different amount of arguments passed in. I believe I have the function most of the way completed but I seem to be getting an infinite loop and am unsure why or how to proceed.

Here is the code I have written so far...

function range(start, stop, step) {
    if (arguments.length===1) {
        start = 0;
        stop = arguments[0];
        step = 1;
    } else if (arguments.length===2) {
        start = arguments[0];
        stop = arguments[1];
        step = 1;
    } else if (arguments.length===3) {
        start = arguments[0];
        stop = arguments[1];
        step = arguments[2];
    }
    // define result array
    let result = [];
    // create a for-loop
    for (start; start < stop; start + step) {
        result.push(start);
    }
    return result;
}

And here are some example calls and their expected outputs...

range(10); -> [0,1,2,3,4,5,6,7,8,9]
range(1,11); -> [1,2,3,4,5,6,7,8,9,10]
range(0,30,5); -> [0,5,10,15,20,25]
range(0,-10,-1); -> [0,-1,-2,-3,-4,-5,-6,-7,-8,-9]

The function is also supposed to be able to do negative ranges with negative 'step' values as well.

Could someone explain to me why I seem to be getting an infinite loop?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Because you don't change start value in your for loop. you have missed an =.

for (start; start < stop; start += step) 
about 4 years ago · Juan Pablo Isaza Denunciar

0

Your code contains several mistake. For example you reassign values to the arguments, which one should never do. Then your for loop only works for stops which are greater than starts. And there is no error checking at all. Here is a self-explaining version which should work:

function range(start, stop, step) {
  for (let i = 0; i < arguments.length; i++) {
    if (!Number.isInteger(arguments[i])) {
      return [ 'Invalid arguments: all arguments must be of type Integer' ]
    }
  }
  let from = 0
  let to = 0
  let increment = 1
  if (arguments.length === 1) {
    to = arguments[0]
  } else if (arguments.length === 2) {
    [ from, to ] = arguments
  } else if (arguments.length === 3) {
    [ from, to, increment ] = arguments
  } else {
    return [ 'Invalid arguments: 0 or more than 3 arguments' ]
  }
  if (increment > 0 && from > to) {
    return [ 'Invalid arguments: step must be negative' ]
  } else if (increment < 0 && from < to) {
    return [ 'Invalid arguments: step must be positive' ]
  } else if (increment === 0) {
    return [ 'Invalid arguments: step cannot be 0' ]
  }
  let result = []
  if (increment > 0) {
    for (from; from < to; from += increment) {
      result.push(from)
    }
  } else {
    for (from; from > to; from += increment) {
      result.push(from)
    }
  }
  return result
}

console.log(range(10))             // [0,1,2,3,4,5,6,7,8,9]
console.log(range(1, 11))          // [1,2,3,4,5,6,7,8,9,10]
console.log(range(0, 30, 5))       // [0,5,10,15,20,25]
console.log(range(0, -10, -1))     // [0,-1,-2,-3,-4,-5,-6,-7,-8,-9]
console.log(range('0', 'abc'))     // Invalid arguments: all arguments must be of type Integer
console.log(range())               // Invalid arguments: 0 or more than 3 arguments
console.log(range(0, -10, 1))      // Invalid arguments: step must be negative
console.log(range(-20, -10, -1))   // Invalid arguments: step must be positive
console.log(range(0, 10, 0))       // Invalid arguments: step cannot be 0

about 4 years ago · Juan Pablo Isaza Denunciar

0

Another range solution:

const range = (start, stop, step) => {
  // manipulation with arguments
  const itemsCout = Math.ceil((stop - start) / step)
  return [...Array(itemsCout)].map((_value, index) => index*step+start )
};

console.log(range(1,10,2)); // [ 1, 3, 5, 7, 9 ]
console.log(range(0,30,5)); // [ 0, 5, 10, 15, 20, 25 ]
console.log(range(0,-10,-1)); // [ 0,-1,-2,-3,-4,-5,-6,-7,-8,-9 ]
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda