Created
August 27, 2019 08:16
-
-
Save zobzn/47965eef9f89cbbdcd6a754937d492db to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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