UNPKG

961 BJavaScriptView Raw
1// Synchronous batching of functions execution
2// Requires ES6 Set
3
4function Batching () {
5 this.active = false
6 this.queue = new Set()
7 this.flushActive = false
8}
9
10Batching.prototype.batch = function (fn) {
11 if (this.active) return fn()
12 this.active = true
13 fn()
14 this.flush()
15 this.active = false
16}
17
18Batching.prototype.flush = function () {
19 if (this.flushActive) return
20 this.flushActive = true
21 while (true) {
22 if (this.queue.size === 0) break
23 var fn = getFirstItem(this.queue)
24 this.queue.delete(fn)
25 fn()
26 }
27 this.flushActive = false
28}
29
30Batching.prototype.add = function (fn) {
31 if (!this.active) return fn()
32 this.queue.add(fn)
33}
34
35function getFirstItem (set) {
36 var first
37 if (set.values) {
38 var it = set.values()
39 first = it.next()
40 return first.value
41 // Shim for IE
42 } else {
43 set.forEach(item => {
44 if (first) return
45 first = item
46 })
47 return first
48 }
49}
50
51module.exports = new Batching()