-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.js
51 lines (43 loc) · 1.06 KB
/
util.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
const current = {};
const events = [];
const valueCount = {};
function get(key) {
return current[key] || null;
}
function set(key, value) {
current[key] && (valueCount[current[key]]--);
value && (valueCount[value] = (valueCount[value] || 0) + 1);
if (events[0]) {
let eventValue = events[events.length - 1][key];
if (eventValue) {
eventValue.current = value;
} else {
events[events.length - 1][key] = { current: value, origin: current[key] };
}
}
current[key] = value;
}
function remove(key) {
set(key, null);
}
function count(value) {
return valueCount[value] || 0;
}
function begin() {
events.push({});
}
function rollback() {
const pop = events.pop();
pop && Object.keys(pop).forEach(key => {
const { current: currentValue, origin } = pop[key];
currentValue && valueCount[currentValue]--;
origin && valueCount[origin]++;
current[key] = origin;
});
}
function commit() {
while (events.length) {
events.pop();
}
}
module.exports = { get, set, count, begin, rollback, commit, delete: remove };