-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLRU_cache.js
More file actions
273 lines (225 loc) · 6.19 KB
/
LRU_cache.js
File metadata and controls
273 lines (225 loc) · 6.19 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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
class Node {
constructor(key, value, next = null, prev = null) {
this.key = key;
this.value = value;
this.next = next;
this.prev = prev;
}
}
class LRU {
//set default limit of 10 if limit is not passed.
constructor(limit = 10) {
this.size = 0;
this.limit = limit;
this.head = null;
this.tail = null;
this.cache = {};
}
// Write Node to head of LinkedList
// update cache with Node key and Node reference
write(key, value){
// console.log(this.head, this.tail)
this.ensureLimit();
if(!this.head){
this.head = this.tail = new Node(key, value);
}else{
const node = new Node(key, value, this.head);
this.head.prev = node;
this.head = node;
}
//Update the cache map
this.cache[key] = this.head;
this.size++;
}
// Read from cache map and make that node as new Head of LinkedList
read(key){
if(this.cache[key]){
const value = this.cache[key].value;
// node removed from it's position and cache
this.remove(key)
// write node again to the head of LinkedList to make it most recently used
this.write(key, value);
return value;
}
console.log(`Item not available in cache for key ${key}`);
}
ensureLimit(){
if(this.size === this.limit){
this.remove(this.tail.key)
}
}
remove(key){
const node = this.cache[key];
if(node.prev !== null){
node.prev.next = node.next;
}else{
this.head = node.next;
}
if(node.next !== null){
node.next.prev = node.prev;
}else{
this.tail = node.prev
}
delete this.cache[key];
this.size--;
}
clear() {
this.head = null;
this.tail = null;
this.size = 0;
this.cache = {};
}
// Invokes the callback function with every node of the chain and the index of the node.
forEach(fn) {
let node = this.head;
let counter = 0;
while (node) {
fn(node, counter);
node = node.next;
counter++;
}
}
// To iterate over LRU with a 'for...of' loop
// *[Symbol.iterator]() {
// let node = this.head;
// while (node) {
// yield node;
// node = node.next;
// }
// }
}
let lruCache = new LRU(3);
lruCache.write('a', 123);
lruCache.write('b', 456);
lruCache.write('c', 789);
lruCache.read('a'); // output 123
// Now max limit 3 is reached. Let's add a new element
lruCache.write('d', 0);
/*
Design a low level design for a Cache system.
Cache system should have support for following operations:
1. Put: This will allow user to put a value against a key in the cache.
2. Get: This will allow user to get the previously saved value using key.
3. Eviction: Cache should also support removal of some key in case cache is full, based on Storage Full Exception Handling and LRU Eviction Policy
4. Eviction Based on Expiry(TTL) / Time Based Eviction
5. Support multiple concurrent read and single write in the cache or Multi Threading Issues
6. API detailing
7. DB Schema
*/
/* Classes and Data Structures */
class CacheEntry {
constructor(key, value, ttl = null) {
this.key = key;
this.value = value;
this.lastAccessedTime = Date.now();
this.ttl = ttl ? Date.now() + ttl : null;
}
isExpired() {
return this.ttl && this.ttl < Date.now();
}
updateAccessTime() {
this.lastAccessedTime = Date.now();
}
}
/* Main cache class */
class Cache {
constructor(capacity) {
this.capacity = capacity;
this.store = new Map();
this.accessOrder = new Map(); // Key: CacheEntry, Value: Last Access Time
}
// case 1
put(key, value, ttl = null) {
if (this.store.size >= this.capacity) {
this.evict();
}
const entry = new CacheEntry(key, value, ttl);
this.store.set(key, entry);
this.updateAccessOrder(entry);
}
// case 2
get(key) {
const entry = this.store.get(key);
if (entry) {
if (entry.isExpired()) {
this.remove(key);
return `Item not available in cache for key ${key}`;
}
entry.updateAccessTime();
this.updateAccessOrder(entry);
return entry.value;
}
return `Item not available in cache for key ${key}`;
}
// case 3
remove(key) {
const entry = this.store.get(key);
if (entry) {
this.accessOrder.delete(entry);
this.store.delete(key);
}
}
// case 4
evict() {
// Evict based on LRU or TTL
this.cleanExpiredEntries();
if (this.store.size >= this.capacity) {
const oldestEntry = this.getOldestEntry();
this.remove(oldestEntry.key);
}
}
cleanExpiredEntries() {
for (let [key, entry] of this.store) {
if (entry.isExpired()) {
this.remove(key);
}
}
}
getOldestEntry() {
return Array.from(this.accessOrder.entries()).reduce((oldest, entry) => {
return (oldest[1] < entry[1]) ? oldest : entry;
})[0];
}
updateAccessOrder(entry) {
this.accessOrder.delete(entry);
this.accessOrder.set(entry, entry.lastAccessedTime);
}
}
/* Case 5 */
/*
In JavaScript (Node.js), you can use async and await to manage asynchronous operations.
To support multiple concurrent reads and a single write, you can use async functions with proper locking mechanisms
*/
// Let's say for PUT example, similary can be for GET also
/*
// Keep this on top outside class
const { Mutex } = require('async-mutex');
async put(key, value, ttl = null) {
const release = await this.mutex.acquire();
try {
if (this.store.size >= this.capacity) {
this.evict();
}
const entry = new CacheEntry(key, value, ttl);
this.store.set(key, entry);
this.updateAccessOrder(entry);
} finally {
release();
}
} */
/* Case 6 */
/*
PUT /cache: Adds a key-value pair to the cache.
Request Body: { "key": "someKey", "value": "someValue", "ttl": 60000 }
GET /cache/:key: Retrieves the value for a given key.
URL Parameter: key
*/
/* Case 7 */
// Although a cache typically resides in-memory, if you need persistence, you can use a simple key-value store schema:
/*
CREATE TABLE Cache (
key VARCHAR PRIMARY KEY,
value TEXT,
ttl BIGINT,
lastAccessedTime BIGINT
); */