1 | "use strict";
|
2 |
|
3 | var Batcher, Events, parser;
|
4 | parser = require("./parser");
|
5 | Events = require("./Events");
|
6 |
|
7 | Batcher = function () {
|
8 | class Batcher {
|
9 | constructor(options = {}) {
|
10 | this.options = options;
|
11 | parser.load(this.options, this.defaults, this);
|
12 | this.Events = new Events(this);
|
13 | this._arr = [];
|
14 |
|
15 | this._resetPromise();
|
16 |
|
17 | this._lastFlush = Date.now();
|
18 | }
|
19 |
|
20 | _resetPromise() {
|
21 | return this._promise = new this.Promise((res, rej) => {
|
22 | return this._resolve = res;
|
23 | });
|
24 | }
|
25 |
|
26 | _flush() {
|
27 | clearTimeout(this._timeout);
|
28 | this._lastFlush = Date.now();
|
29 |
|
30 | this._resolve();
|
31 |
|
32 | this.Events.trigger("batch", this._arr);
|
33 | this._arr = [];
|
34 | return this._resetPromise();
|
35 | }
|
36 |
|
37 | add(data) {
|
38 | var ret;
|
39 |
|
40 | this._arr.push(data);
|
41 |
|
42 | ret = this._promise;
|
43 |
|
44 | if (this._arr.length === this.maxSize) {
|
45 | this._flush();
|
46 | } else if (this.maxTime != null && this._arr.length === 1) {
|
47 | this._timeout = setTimeout(() => {
|
48 | return this._flush();
|
49 | }, this.maxTime);
|
50 | }
|
51 |
|
52 | return ret;
|
53 | }
|
54 |
|
55 | }
|
56 |
|
57 | ;
|
58 | Batcher.prototype.defaults = {
|
59 | maxTime: null,
|
60 | maxSize: null,
|
61 | Promise: Promise
|
62 | };
|
63 | return Batcher;
|
64 | }.call(void 0);
|
65 |
|
66 | module.exports = Batcher; |
\ | No newline at end of file |