Skip to content

Instantly share code, notes, and snippets.

@zobzn
Created August 27, 2019 08:16
Show Gist options
  • Save zobzn/47965eef9f89cbbdcd6a754937d492db to your computer and use it in GitHub Desktop.
Save zobzn/47965eef9f89cbbdcd6a754937d492db to your computer and use it in GitHub Desktop.
"use strict";
class Batcher {
constructor(size = 10, callback = () => {}) {
this.size = size;
this.queue = [];
this.callback = callback;
}
static create(size = 10, callback = () => {}) {
return new Batcher(size, callback);
}
async add(item) {
this.queue.push(item);
if (this.queue.length >= this.size) {
await this._process();
}
}
async finish() {
if (this.queue.length) {
await this._process();
}
}
async _process() {
const items = [];
while (this.queue.length) {
const item = this.queue.shift();
items.push(item);
}
if (items.length) {
await this.callback(items);
}
}
}
module.exports = Batcher;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment