-
Notifications
You must be signed in to change notification settings - Fork 0
/
LRU.ts
114 lines (90 loc) · 2.53 KB
/
LRU.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
import { NewLineKind } from "typescript";
type Node<T> = {
value: T,
next?: Node<T>;
prev?: Node<T>;
}
function createNode<V>(value: V): Node<V>{
return {value};
}
export default class LRU<K, V> {
private length: number;
private head?: Node<V>;
private tail?: Node<V>;
private lookup: Map<K, Node<V>>;
private reverseLookup: Map<Node<V>, K>;
constructor(private capacity: number = 10) {
this.length = 0;
this.head = this.tail = undefined;
this.lookup = new Map<K, Node<V>>();
this.reverseLookup = new Map<Node<V>, K>();
}
update(key: K, value: V): void {
// does it exist?
let node = this.lookup.get(key);
if (!node){
node = createNode(value);
this.length++;
this.prepend(node);
this.trimCache();
this.lookup.set(key, node);
this.reverseLookup.set(node, key);
} else {
this.detach(node);
this.prepend(node);
node.value = value;
}
// if it doesn't, we need to insert
// - check capacity and evict if over
// if it does, we need to update to the front of the list
// and update the value
}
get(key: K): V | undefined {
const node = this.lookup.get(key);
if (!node){
return undefined;
}
this.detach(node);
this.prepend(node);
return node.value;
}
private detach(node: Node<V>){
if(node.prev){
node.prev.next = node.next;
}
if(node.next){
node.next.prev = node.prev;
}
// if (this.length === 1){
// this.tail = this.head = undefined;
// }
if (this.head === node){
this.head = this.head.next;
}
if(this.tail === node){
this.tail = this.tail.prev;
}
node.next = undefined;
node.prev = undefined;
}
private prepend(node: Node<V>){
if(!this.head){
this.head = this.tail = node;
return;
}
node.next = this.head;
this.head.prev = node;
this.head = node;
}
private trimCache(): void{
if(this.length <= this.capacity){
return;
}
const tail = this.tail as Node<V>;
this.detach(this.tail as Node<V>);
const key = this.reverseLookup.get(tail) as K;
this.lookup.delete(key);
this.reverseLookup.delete(tail);
this.length--;
}
}