Skip to content

Commit 7d8ef9e

Browse files
authored
Create LRU Cache.js
1 parent 8513b9a commit 7d8ef9e

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed

LRU Cache.js

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
/**
2+
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
3+
4+
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
5+
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
6+
*/
7+
class Node {
8+
constructor(key, val) {
9+
this.key = key;
10+
this.val = val;
11+
this.next = null;
12+
this.prev = null;
13+
}
14+
}
15+
/**
16+
* @constructor
17+
*/
18+
var LRUCache = function(capacity) {
19+
this.list = null;
20+
this.map = new Map();
21+
this.head = null;
22+
this.tail = null;
23+
this.size = capacity;
24+
this.curSize = 0;
25+
};
26+
27+
/**
28+
* @param {number} key
29+
* @returns {number}
30+
*/
31+
LRUCache.prototype.get = function(key) {
32+
if (!this.map.get(key)) {
33+
return -1;
34+
}
35+
36+
let node = this.map.get(key);
37+
38+
if (node === this.head) {
39+
return node.val;
40+
}
41+
42+
// remove node from list
43+
if (node === this.tail) {
44+
this.tail.prev.next = null;
45+
this.tail = this.tail.prev;
46+
} else {
47+
node.prev.next = node.next;
48+
node.next.prev = node.prev;
49+
}
50+
51+
// insert node to head
52+
node.next = this.head;
53+
this.head.prev = node;
54+
this.head = node;
55+
56+
return node.val;
57+
};
58+
59+
/**
60+
* @param {number} key
61+
* @param {number} value
62+
* @returns {void}
63+
*/
64+
LRUCache.prototype.set = function(key, value) {
65+
let newNode = new Node(key, value);
66+
67+
if (this.curSize === 0) {
68+
this.head = newNode;
69+
this.tail = newNode;
70+
this.curSize++;
71+
} else {
72+
newNode.next = this.head;
73+
this.head.prev = newNode;
74+
this.head = newNode;
75+
this.curSize++;
76+
}
77+
78+
// update
79+
if (this.map.get(key)) {
80+
let oldNode = this.map.get(key);
81+
82+
if (oldNode === this.tail) {
83+
this.tail = this.tail.prev;
84+
this.tail.next = null;
85+
} else {
86+
oldNode.prev.next = oldNode.next;
87+
oldNode.next.prev = oldNode.prev;
88+
}
89+
90+
this.curSize--;
91+
this.map.set(key, newNode);
92+
} else {
93+
if (this.curSize > this.size) {
94+
//delete tail
95+
this.map.delete(this.tail.key);
96+
this.tail = this.tail.prev;
97+
this.tail.next = null;
98+
this.curSize--;
99+
}
100+
101+
this.map.set(key, newNode);
102+
}
103+
};

0 commit comments

Comments
 (0)