forked from simpleledger/SLPDB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.ts
97 lines (79 loc) · 1.77 KB
/
cache.ts
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
export class CacheSet<T> {
private set = new Set<T>()
private list: T[] = [];
private maxSize: number;
constructor(maxSize: number) {
this.maxSize = maxSize;
}
get length(): number {
return this.list.length;
}
push(item: T) {
this.set.add(item);
this.list.push(item);
if(this.set.size > this.maxSize) {
this.shift();
}
}
has(item: T) {
return this.set.has(item);
}
delete(item: T) {
if(this.set.delete(item))
this.list = this.list.filter(k => k !== item);
}
toSet() {
return this.set;
}
shift(): T | undefined {
let item = this.list.shift();
if(item)
this.set.delete(item);
return item;
}
clear() {
this.list = [];
this.set.clear();
}
}
export class CacheMap<T, M> {
private map = new Map<T, M>()
private list: T[] = [];
private maxSize: number;
constructor(maxSize: number) {
this.maxSize = maxSize;
}
get length(): number {
return this.list.length;
}
set(key: T, item: M) {
this.list.push(key);
this.map.set(key, item);
if(this.map.size > this.maxSize) {
this.shift();
}
}
get(key: T) {
return this.map.get(key);
}
has(key: T) {
return this.map.has(key);
}
delete(key: T) {
if(this.map.delete(key))
this.list = this.list.filter(k => k !== key);
}
toMap() {
return this.map;
}
private shift(): T | undefined {
let key = this.list.shift();
if(key)
this.map.delete(key);
return key;
}
clear() {
this.list = [];
this.map.clear();
}
}