Skip to content

Commit 7e5dffe

Browse files
committed
LRU Cache using Singly Linked List
1 parent 4cc4578 commit 7e5dffe

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
class LRUCache {
2+
constructor(capacity) {
3+
this.capacity = capacity;
4+
this.cache = {};
5+
this.head = null;
6+
this.tail = null;
7+
}
8+
9+
get(key) {
10+
if (this.cache[key]) {
11+
this.moveToFront(key);
12+
return this.cache[key].value;
13+
}
14+
return null;
15+
}
16+
17+
put(key, value) {
18+
if (this.cache[key]) {
19+
this.cache[key].value = value;
20+
this.moveToFront(key);
21+
} else {
22+
if (Object.keys(this.cache).length === this.capacity) {
23+
this.removeLast();
24+
}
25+
this.addToFront(key, value);
26+
}
27+
}
28+
29+
addToFront(key, value) {
30+
const newNode = {key, value, next: null};
31+
if (!this.head) {
32+
this.head = newNode;
33+
this.tail = newNode;
34+
} else {
35+
newNode.next = this.head;
36+
this.head = newNode;
37+
}
38+
this.cache[key] = newNode;
39+
}
40+
41+
removeLast() {
42+
if (!this.head) return;
43+
44+
const lastKey = this.tail.key;
45+
delete this.cache[lastKey];
46+
47+
if (this.head === this.tail) {
48+
this.head = null;
49+
this.tail = null;
50+
} else {
51+
let current = this.head;
52+
while (current.next !== this.tail) {
53+
current = current.next;
54+
}
55+
56+
current.next = null;
57+
this.tail = current;
58+
}
59+
}
60+
61+
moveToFront(key) {
62+
const current = this.cache[key];
63+
64+
if (current === this.head) return;
65+
66+
let prev = null;
67+
let node = this.head;
68+
while (node && node.key !== key) {
69+
prev = node;
70+
node = node.next;
71+
}
72+
73+
if (!node) return;
74+
75+
if (node === this.tail) {
76+
this.tail = prev;
77+
}
78+
79+
if (prev) {
80+
prev.next = node.next;
81+
}
82+
83+
node.next = this.head;
84+
this.head = node;
85+
}
86+
}
87+
88+
// Custom Hook in React JS 👇
89+
import {useRef} from "react";
90+
91+
const useLRUCache = (capacity) => {
92+
const cacheRef = useRef(new LRUCache(capacity));
93+
console.log(cacheRef.current);
94+
95+
const get = (key) => cacheRef.current.get(key);
96+
const put = (key, value) => cacheRef.current.put(key, value);
97+
98+
return {get, put};
99+
};
100+
101+
export default useLRUCache;

0 commit comments

Comments
 (0)