forked from ufosc/Club_Website_2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.js
50 lines (43 loc) · 1.1 KB
/
cache.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
class Cache {
constructor () {
this.sync = true
this.state = {}
this.callbacks = []
}
register (...callbacks) {
for (let i = 0; i < callbacks.length; i++) {
this.callbacks.push(callbacks[i])
// Call callback immediately so that Cache()
// outputs are defined.
const response = callbacks[i]()
this.state = { ...this.state, ...response }
}
}
run () {
for (const callback of this.callbacks) {
// Wrap callback in async function so state can be updated
// parallely.
const runAsync = async () => {
const response = await callback()
this.state = { ...this.state, ...response }
}
runAsync()
}
}
start (interval) {
if (typeof (interval) !== 'number') { return new Error('Expected interval to be of type number') }
// Run AT MOST once every 'interval' milliseconds
setInterval(() => {
if (this.sync) {
this.run()
this.sync = false
}
}, interval)
}
Cache () {
// Start syncing again
this.sync = true
return this.state
}
}
module.exports = Cache