This repository has been archived by the owner on May 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdebounce-batch.js
74 lines (69 loc) · 2.08 KB
/
debounce-batch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// SPDX-FileCopyrightText: 2021 Anders Rune Jensen
//
// SPDX-License-Identifier: LGPL-3.0-only
module.exports = class DebouncingBatchAdd {
constructor(addBatch, period) {
this.addBatch = addBatch
this.period = period
this.queueByAuthor = new Map()
this.timestampsByAuthor = new Map()
this.timer = null
}
flush(authorId) {
const queue = this.queueByAuthor.get(authorId)
const n = queue.length
const msgVals = queue.map((x) => x[0])
// Clear the queue memory BEFORE the callbacks trigger more queue additions
this.queueByAuthor.delete(authorId)
this.timestampsByAuthor.delete(authorId)
// Add the messages in the queue
this.addBatch(msgVals, (err, kvts) => {
if (err) {
for (let i = 0; i < n; ++i) {
const cb = queue[i][1]
cb(err)
}
} else if (kvts.length !== n) {
for (let i = 0; i < n; ++i) {
const cb = queue[i][1]
cb(new Error(`unexpected addBatch mismatch: ${kvts.length}} != ${n}`))
}
} else {
for (let i = 0; i < n; ++i) {
const kvt = kvts[i]
const cb = queue[i][1]
cb(null, kvt)
}
}
})
}
scheduleFlush() {
// Timer is already enabled
if (this.timer) return
this.timer = setInterval(() => {
// Turn off the timer if there is nothing to flush
if (this.queueByAuthor.size === 0) {
clearInterval(this.timer)
this.timer = null
}
// For each author, flush if enough time has passed
else {
const now = Date.now()
for (const authorId of this.queueByAuthor.keys()) {
const lastAdded = this.timestampsByAuthor.get(authorId)
if (now - lastAdded > this.period) {
this.flush(authorId)
}
}
}
}, this.period * 0.5)
}
add(msgVal, cb) {
const authorId = msgVal.author
const queue = this.queueByAuthor.get(authorId) || []
queue.push([msgVal, cb])
this.queueByAuthor.set(authorId, queue)
this.timestampsByAuthor.set(authorId, Date.now())
this.scheduleFlush()
}
}