Home > OS >  Looping in batches without repeating
Looping in batches without repeating

Time:02-26

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

CodePudding user response:

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

  • Related