Batch Collector Time And Size Flush
Collect items into a batch and flush by size threshold or timer whichever fires first for efficient bulk API submission.
Code
export function batchCollector(flush,{maxSize=100,maxWait=5000}={}){let batch=[],timer=null;function schedule(){if(!timer&&maxWait<Infinity)timer=setTimeout(()=>{timer=null;doFlush();},maxWait);}async function doFlush(){if(batch.length===0)return;const cur=batch;batch=[];await flush(cur);}function add(item){batch.push(item);if(batch.length>=maxSize){if(timer){clearTimeout(timer);timer=null;}doFlush();}else schedule();}add.flush=doFlush;add.size=()=>batch.length;return add;}Report a problem with this exampleOpens a pre-filled issue on GitHub.