-
Notifications
You must be signed in to change notification settings - Fork 7
/
status.js
73 lines (65 loc) · 1.46 KB
/
status.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
// SPDX-FileCopyrightText: 2021 Anders Rune Jensen
//
// SPDX-License-Identifier: LGPL-3.0-only
const Obv = require('obz')
module.exports = function Status() {
let indexesStatus = {}
const obv = Obv()
obv.set(indexesStatus)
const EMIT_INTERVAL = 1000 // ms
let i = 0
let iTimer = 0
let timer = null
const activeIndexNames = new Set()
function setTimer() {
// Turn on
timer = setInterval(() => {
if (i === iTimer) {
// Turn off because nothing has been updated recently
clearInterval(timer)
timer = null
i = iTimer = 0
} else {
iTimer = i
obv.set(indexesStatus)
}
}, EMIT_INTERVAL)
if (timer.unref) timer.unref()
}
function update(indexes, names) {
let changed = false
for (const name of names) {
const index = indexes.get(name)
const previous = indexesStatus[name] || -Infinity
if (index.offset > previous) {
indexesStatus[name] = index.offset
activeIndexNames.add(name)
changed = true
}
}
if (!changed) return
++i
if (!timer) {
iTimer = i
obv.set(indexesStatus)
setTimer()
}
}
function done(names) {
for (const name of names) activeIndexNames.delete(name)
if (activeIndexNames.size === 0) {
indexesStatus = {}
++i
if (!timer) {
iTimer = i
obv.set(indexesStatus)
setTimer()
}
}
}
return {
obv,
done,
update,
}
}