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

98
Visualizações
Looping in batches without repeating

Sorry if this is a stupid question but I'm new to programming and trying to write a loop that processes things in batches.

const totalPages = 13;
const batchSize = 3;
const startFrom = 0;
let processed = startFrom || 1;

while (processed < totalPages) {
    let start = processed; 
    let end = Math.min(start + batchSize, totalPages); 
    console.log(`processing batch: ${start}-${end}`); 
    processed = end;
}

Outputs:

processing batch: 1-4
processing batch: 4-7
processing batch: 7-10
processing batch: 10-13

However the start and end are not what I expect, I need it to be:

processing batch: 1-3
processing batch: 4-6
processing batch: 7-9
processing batch: 10-12
processing batch: 13-13
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You start out with processed equal to 1, but that is not true: at that moment you have not "processed" anything yet, so it should be 0. On the other hand start should not be made equal to processed, but to one more -- as it is the next one after those that have already been processed.

Alter the other expressions accordingly:

const totalPages = 13;
const batchSize = 3;
const startFrom = 0;
let processed = startFrom;

while (processed < totalPages) {
    let start = processed + 1; 
    let end = Math.min(processed + batchSize, totalPages); 
    console.log(`processing batch: ${start}-${end}`); 
    processed = end;
}

It is more common to use a for loop for this. You could also have the parameters as function parameters. Finally, startFrom is maybe not a good name for that variable, as it suggests a number of an item (starting from 1). I would suggest skip, so that 0 means nothing should be skipped:

function printBatches(totalPages, batchSize, skip=0) {
    for (let processed = skip; processed < totalPages; processed += batchSize) {
        let start = processed + 1;
        let end = Math.min(processed + batchSize, totalPages); 
        console.log(`processing batch: ${start}-${end}`); 
    }
}

printBatches(13, 3);

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