-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPersistentRingBuffer.js
77 lines (65 loc) · 1.53 KB
/
PersistentRingBuffer.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
class PersistentRingBuffer {
constructor(prefix, capacity) {
this.prefix = prefix;
this.capacity = capacity;
this.end = 0;
this.size = 0;
this.loadMetadata();
}
endItemName() {
return this.prefix + this.end;
}
loadMetadata() {
let end = localStorage.getItem(this.prefix + "end");
let size = localStorage.getItem(this.prefix + "size");
if (end === null || size === null) {
return;
}
end = parseInt(end);
size = parseInt(size);
if (size > this.capacity) {
throw "PersistentRingBuffer: size " + size + "> capacity " + this.capacity;
}
this.end = end;
this.size = size;
}
saveMetadata() {
localStorage.setItem(this.prefix + "end", this.end);
localStorage.setItem(this.prefix + "size", this.size);
}
push(value) {
localStorage.setItem(this.endItemName(), JSON.stringify(value));
if (++this.end >= this.capacity) {
this.end = 0;
}
if (this.size < this.capacity) {
this.size += 1;
}
this.saveMetadata();
}
pop() {
if (this.size === 0) {
return;
}
if (--this.end < 0) {
this.end += this.capacity;
}
this.size--;
this.saveMetadata();
let name = this.endItemName();
let result = localStorage.getItem(name);
localStorage.removeItem(name);
return JSON.parse(result);
}
};
function _ringBufferTest() {
localStorage.clear();
let buf = new PersistentRingBuffer('test', 2);
buf.push(1);
buf.push(2);
buf.push(3);
console.assert(buf.pop() === 3);
console.assert(buf.pop() === 2);
console.assert(buf.pop() === undefined);
buf.push("persistent");
}