-
Notifications
You must be signed in to change notification settings - Fork 205
Expand file tree
/
Copy pathcode.js
More file actions
242 lines (200 loc) · 5.8 KB
/
code.js
File metadata and controls
242 lines (200 loc) · 5.8 KB
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
// Import visualization library
const {
Array1DTracer,
LogTracer,
Layout,
Tracer,
} = require("algorithm-visualizer");
/**
* Node class for doubly-linked list
*/
class Node {
constructor(key, value) {
this.key = key;
this.value = value;
this.next = null;
this.prev = null;
}
}
/**
* LRU (Least Recently Used) Cache Implementation
*
* This cache maintains a fixed capacity and automatically evicts
* the least recently used item when capacity is exceeded.
*
* Time Complexity: O(1) for both get and put operations
* Space Complexity: O(capacity)
*/
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.size = 0;
this.head = null;
this.map = new Map();
}
/**
* Get value by key. Marks the key as recently used.
* Returns -1 if key doesn't exist.
*/
get(key) {
if (!this.map.has(key)) return -1;
this.moveToFront(key);
return this.map.get(key).value;
}
/**
* Insert or update a key-value pair.
* If cache is full, evicts the least recently used item.
*/
put(key, value) {
if (this.map.has(key)) {
const node = this.map.get(key);
node.value = value;
this.moveToFront(key);
return;
}
const newNode = new Node(key, value);
this.map.set(key, newNode);
this.insertAtFront(newNode);
if (this.size > this.capacity) {
this.removeLast();
}
}
/**
* Get current cache state as array
*/
getState() {
const result = [];
let current = this.head;
while (current) {
result.push({ key: current.key, value: current.value });
current = current.next;
if (current === this.head) break;
}
return result;
}
insertAtFront(node) {
if (!this.head) {
node.next = node;
node.prev = node;
this.head = node;
} else {
const last = this.head.prev;
node.next = this.head;
node.prev = last;
last.next = node;
this.head.prev = node;
this.head = node;
}
this.size++;
}
removeLast() {
if (!this.head) return;
const last = this.head.prev;
this.map.delete(last.key);
this.size--;
if (this.head === last) {
this.head = null;
return;
}
last.prev.next = this.head;
this.head.prev = last.prev;
}
moveToFront(key) {
const node = this.map.get(key);
if (node === this.head) return;
node.prev.next = node.next;
node.next.prev = node.prev;
const last = this.head.prev;
node.next = this.head;
node.prev = last;
last.next = node;
this.head.prev = node;
this.head = node;
}
}
// Visualization Setup
const logger = new LogTracer("Operation Log");
const cacheTracer = new Array1DTracer(
"LRU Cache State (Most Recent → Least Recent)"
);
// Helper function to update visualization
function updateVisualization(cache, message) {
const state = cache.getState();
const keys = state.map((item) => `${item.key}:${item.value}`);
if (keys.length > 0) {
cacheTracer.set(keys);
cacheTracer.patch(0); // Highlight most recently used
}
logger.println(message);
Tracer.delay();
}
// Set up layout
Layout.setRoot(cacheTracer);
Tracer.delay();
// Demo: LRU Cache Operations
logger.println("=== LRU Cache Demonstration ===");
logger.println(`Creating cache with capacity 4`);
Tracer.delay();
const cache = new LRUCache(4);
// Operation 1: Insert items
logger.println("\n--- Inserting Items ---");
Tracer.delay();
cache.put(1, 100);
updateVisualization(cache, "PUT(1, 100): Added first item");
cache.put(2, 200);
updateVisualization(cache, "PUT(2, 200): Added second item");
cache.put(3, 300);
updateVisualization(cache, "PUT(3, 300): Added third item");
cache.put(4, 400);
updateVisualization(cache, "PUT(4, 400): Cache is now full");
// Operation 2: Access an item (makes it most recently used)
logger.println("\n--- Accessing Items ---");
Tracer.delay();
const value1 = cache.get(1);
updateVisualization(cache, `GET(1): Retrieved value ${value1}, moved to front`);
const value2 = cache.get(3);
updateVisualization(cache, `GET(3): Retrieved value ${value2}, moved to front`);
// Operation 3: Insert new item (will evict least recently used)
logger.println("\n--- Eviction Demonstration ---");
Tracer.delay();
cache.put(5, 500);
updateVisualization(cache, "PUT(5, 500): Added new item, evicted key 2 (LRU)");
// Try to access evicted item
const evicted = cache.get(2);
logger.println(`GET(2): Returns ${evicted} (not found - was evicted)`);
Tracer.delay();
// Operation 4: Update existing item
logger.println("\n--- Updating Items ---");
Tracer.delay();
cache.put(1, 150);
updateVisualization(
cache,
"PUT(1, 150): Updated value of key 1, moved to front"
);
// Operation 5: More operations to show LRU behavior
logger.println("\n--- Complex Access Pattern ---");
Tracer.delay();
cache.get(4);
updateVisualization(cache, "GET(4): Accessed key 4, moved to front");
cache.put(6, 600);
updateVisualization(cache, "PUT(6, 600): Added new item, evicted key 5 (LRU)");
cache.get(1);
updateVisualization(cache, "GET(1): Accessed key 1, moved to front");
cache.put(7, 700);
updateVisualization(cache, "PUT(7, 700): Added new item, evicted key 3 (LRU)");
// Final state
logger.println("\n--- Final Cache State ---");
Tracer.delay();
const finalState = cache.getState();
logger.println("Cache contents (Most Recent → Least Recent):");
finalState.forEach((item, index) => {
logger.println(` ${index + 1}. Key: ${item.key}, Value: ${item.value}`);
});
Tracer.delay();
logger.println("\n=== Demonstration Complete ===");
logger.println("\nKey Observations:");
logger.println("1. Most recently accessed items stay at the front");
logger.println("2. When cache is full, least recently used item is evicted");
logger.println("3. Both GET and PUT operations update recency");
logger.println("4. All operations run in O(1) time complexity");
Tracer.delay();