-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathutils.js
53 lines (45 loc) · 984 Bytes
/
utils.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
// SPDX-FileCopyrightText: 2021-2022 Anders Rune Jensen
//
// SPDX-License-Identifier: LGPL-3.0-only
/**
* Obv utility to run the `cb` once, as soon as the condition given by
* `filter` is true.
*/
function onceWhen(obv, filter, cb) {
if (!obv) return cb()
let answered = false
let remove
remove = obv((x) => {
if (answered) return
if (!filter(x)) return
answered = true
cb()
if (!remove) return
setTimeout(() => {
if (!remove) return
remove()
remove = null
})
})
}
function onceWhenPromise(obv, filter) {
return new Promise((resolve) => {
onceWhen(obv, filter, resolve)
})
}
class ReadyGate {
constructor() {
this.waiting = new Set()
this.ready = false
}
onReady(cb) {
if (this.ready) cb()
else this.waiting.add(cb)
}
setReady() {
this.ready = true
for (const cb of this.waiting) cb()
this.waiting.clear()
}
}
module.exports = { onceWhen, onceWhenPromise, ReadyGate }