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

97
Vistas
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 Respuestas
Responde la pregunta

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 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