Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda