|
| 1 | +class SingletonBatcher { |
| 2 | + static instance; |
1 | 3 |
|
| 4 | + constructor(handleBatch, maxSize, maxTime) { |
| 5 | + if (SingletonBatcher.instance) { |
| 6 | + SingletonBatcher.instance.handleBatch = handleBatch; |
| 7 | + SingletonBatcher.instance.maxSize = maxSize; |
| 8 | + SingletonBatcher.instance.maxTime = maxTime; |
2 | 9 |
|
3 | | -function createBatcher(handleBatch, maxSize, maxTime) { |
4 | | - return { |
5 | | - dataArray: [], |
6 | | - // using closure, so no need to keep as part of the object. |
7 | | - // maxSize: maxSize, |
8 | | - // maxTime: maxTime, |
9 | | - add: function(data) { |
10 | | - this.dataArray.push(data); |
11 | | - if (this.dataArray.length >= maxSize) { |
12 | | - this.flush(); |
13 | | - } else if (maxTime && this.dataArray.length === 1) { |
14 | | - var self = this; |
15 | | - this._timeout = setTimeout(function() { |
16 | | - self.flush(); |
17 | | - }, maxTime); |
18 | | - } |
19 | | - }, |
20 | | - flush: function() { |
21 | | - // note, in case the handleBatch is a |
22 | | - // delayed function, then it swaps before |
23 | | - // sending the current data. |
24 | | - clearTimeout(this._timeout); |
25 | | - this._lastFlush = Date.now(); |
26 | | - var currentDataArray = this.dataArray; |
27 | | - this.dataArray = []; |
28 | | - handleBatch(currentDataArray); |
29 | | - } |
30 | | - }; |
| 10 | + return SingletonBatcher.instance; |
| 11 | + } |
| 12 | + this.dataArray = []; |
| 13 | + this.handleBatch = handleBatch; |
| 14 | + this.maxSize = maxTime; |
| 15 | + SingletonBatcher.instance = this; |
| 16 | + } |
| 17 | + |
| 18 | + add(data) { |
| 19 | + this.dataArray.push(data); |
| 20 | + if (this.dataArray.length >= this.maxSize) { |
| 21 | + this.flush(); |
| 22 | + } else if (this.maxTime && this.dataArray.length === 1) { |
| 23 | + var self = this; |
| 24 | + this._timeout = setTimeout(() => { |
| 25 | + self.flush(); |
| 26 | + }, this.maxTime); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + flush() { |
| 31 | + // note, in case the handleBatch is a |
| 32 | + // delayed function, then it swaps before |
| 33 | + // sending the current data. |
| 34 | + clearTimeout(this._timeout); |
| 35 | + this._lastFlush = Date.now(); |
| 36 | + var currentDataArray = this.dataArray; |
| 37 | + this.dataArray = []; |
| 38 | + this.handleBatch(currentDataArray); |
31 | 39 | } |
32 | | - |
33 | | - module.exports = createBatcher; |
| 40 | +} |
| 41 | + |
| 42 | +function createBatcher(handleBatch, maxSize, maxTime) { |
| 43 | + return new SingletonBatcher(handleBatch, maxSize, maxTime); |
| 44 | +} |
| 45 | + |
| 46 | +module.exports = createBatcher; |
0 commit comments