-
Notifications
You must be signed in to change notification settings - Fork 33
/
cache.ts
135 lines (110 loc) · 2.55 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
export class CacheSet<T> {
private set = new Set<T>()
private list: T[] = [];
private maxSize: number;
constructor(maxSize: number) {
this.maxSize = maxSize;
}
[Symbol.iterator]() {
return this.list.values();
}
get length(): number {
return this.list.length;
}
push(item: T) {
this.set.add(item);
if (this.maxSize > 0 && this.set.size > this.maxSize) {
this.shift();
}
return this.list.push(item);
}
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;
}
pop(): T | undefined {
let item = this.list.pop();
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;
}
[Symbol.iterator]() {
return this.items();
}
get length(): number {
return this.list.length;
}
get size(): number {
return this.list.length;
}
values(): IterableIterator<M> {
let l: M[] = this.list.map(i => this.map.get(i)!);
return l.values();
}
keys(): IterableIterator<T> {
return this.list.values();
}
items(): IterableIterator<[T,M]> {
let l: [T,M][] = this.list.map(i => [i, this.map.get(i)!]);
return l.values();
}
set(key: T, item: M) {
this.list.push(key);
this.map.set(key, item);
if(this.maxSize > 0 && 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();
}
}