Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!