JSFiddle - React, Tailwind, and code Playground
by MartijnR
JavaScript
var a = [1000000, 2000000, 3000000, 4000000];
function splitInChunks(sizes, limit){
var i, j, batch, batchSize,
batches = [];
for (i=0; i<sizes.length ; i++){
sizes[i] = {'index': i, 'size': sizes[i]};
}
limit = limit || 5 * 1024 * 1024;
while( sizes.length > 0){
batch = [sizes[0].index];
console.log('batch so far:', batch);
batchSize = sizes[0].size;
if (sizes[0].size < limit){
console.log('still some space in batch');
for (i = 1; i<sizes.length; i++){
console.log('batchSize so far: '+batchSize);
console.log('checking item with size:'+sizes[i].size);
console.log('batchSize + next:' + ( batchSize + sizes[i].size ) );
console.log('limit:'+limit);
if (( batchSize + sizes[i].size) < limit){
console.log('pushing another index onto batch: '+i);
batch.push(sizes[i].index);
batchSize += sizes[i].size;
}
}
}
batches.push(batch);
for (i=0; i<sizes.length; i++){
batchloop:
for (j=0; j<batch.length; j++){
if (sizes[i].index === batch[j]){
console.log('removing index:'+i);
sizes.splice(i, 1);
//break batchloop;
}
}
}
}
return batches;
}
console.log(splitInChunks(a));
document.write(splitInChunks(a));