-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
91 lines (78 loc) · 1.74 KB
/
index.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
class List<K, T> {
key: K;
data: T;
next: List<K, T>;
prev: List<K, T>;
constructor(
key: K,
data: T,
next: List<K, T> = null,
prev: List<K, T> = null
) {
this.key = key;
this.data = data;
this.next = next;
this.prev = prev;
}
public static dummy() {
return new List(null, null);
}
}
export class LRUCache<K, T> {
private hash: Map<K, List<K, T>>;
private SIZE: number;
private mru: List<K, T>;
private lru: List<K, T>;
constructor(SIZE: number) {
this.SIZE = SIZE;
this.hash = new Map();
this.lru = List.dummy();
this.mru = List.dummy();
this.lru.next = this.mru;
this.mru.prev = this.lru;
}
private remove(node: List<K, T>) {
let next = node.next;
let prev = node.prev;
prev.next = next;
next.prev = prev;
}
private add(node: List<K, T>) {
node.next = this.mru;
node.prev = this.mru.prev;
this.mru.prev.next = node;
this.mru.prev = node;
}
public has(key: K): boolean {
return this.hash.has(key);
}
public isFull(): boolean {
return this.hash.size === this.SIZE;
}
public set(key: K, data: T): number {
if (this.has(key)) {
let node = this.hash.get(key);
node.data = data;
this.remove(node);
this.add(node);
} else {
if (this.isFull()) {
this.hash.delete(this.lru.next.key);
this.remove(this.lru.next);
this.add(new List(key, data));
} else
this.add(new List(key, data));
}
this.hash.set(key, this.mru.prev);
return this.hash.size;
}
public get(key: K): T | null {
if (!this.has(key)) {
return null;
}
let node = this.hash.get(key);
this.remove(node);
this.add(node);
return node.data;
}
}