-
Notifications
You must be signed in to change notification settings - Fork 0
/
shared-state.js
104 lines (96 loc) · 2.26 KB
/
shared-state.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
function SharedState({
author,
storage
}) {
this.author = author;
this.storage = new Map(storage || [])
this.callHooks('afterCreate')
}
SharedState.__proto__.hooks = {
afterCreate: [],
afterInsert: [],
afterSync: [],
publish: []
}
SharedState.prototype.callHooks = function (hook, data) {
SharedState.__proto__.hooks[hook].forEach((fun) => {
fun(this, data)
})
}
SharedState.prototype.insert = function (key, data, bleachTTL = 30, area) {
if (bleachTTL === 0) {
this.storage.get(area).delete(key)
this.changed = true
this.callHooks('afterInsert', {
key,
data,
bleachTTL,
area
})
return;
};
const subStorage = this.storage.get(area)
if (!subStorage) {
this.storage.set(area, new Map())
}
this.storage.get(area)
.set(
key, {
author: this.author,
bleachTTL,
data
}
)
this.changed = true
this.callHooks('afterInsert', {
key,
data,
bleachTTL,
area
})
}
SharedState.prototype.show = function (area) {
if (!this.storage.get(area)) {
this.storage.set(area, new Map())
}
return this.storage.get(area);
}
SharedState.prototype.merge = function (stateSlice, _, area) {
if (!this.storage.get(area)) {
this.storage.set(area, new Map())
}
stateSlice.forEach((value, key) => {
if (value.bleachTTL <= 0) {
console.log("debug", "sharedState.merge got expired entry.")
this.changed = true
} else {
let lv = this.storage.get(area).get(key)
if (!lv) {
this.storage.get(area).set(key, value)
} else if (lv && lv.bleachTTL < value.bleachTTL) {
console.log("debug", "Updating entry for: " + key + " older: " + lv.bleachTTL + " newer: " + value.bleachTTL)
this.storage.get(area).set(key, value)
}
}
})
}
SharedState.prototype.remove = function (key, area) {
this.insert(key, {}, 0, area)
}
SharedState.prototype.bleach = function (area) {
let substancialChange = false;
this.storage.get(area).forEach((value, key, storageArea) => {
if (value.bleachTTL < 2) {
storageArea.delete(key)
substancialChange = true
} else {
storageArea.set(key, {
...value,
bleachTTL: value.bleachTTL - 1
})
}
})
this.changed = substancialChange;
return substancialChange;
}
module.exports = SharedState