Skip to content

Commit dfe6473

Browse files
committed
LRU Cache with hash table and double linked list
1 parent 58054dc commit dfe6473

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

‎lru-cache.js

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
var DEBUG = process.env.DEBUG;
2+
3+
function Node(k, v, prev, next) {
4+
this.k = k;
5+
this.v = v;
6+
this.prev = prev;
7+
this.next = next;
8+
}
9+
10+
Node.prototype.remove = function () {
11+
var prev = this.prev;
12+
var next = this.next;
13+
prev.next = next;
14+
next.prev = prev;
15+
};
16+
Node.prototype.insertAfter = function (node) {
17+
var next = this.next;
18+
this.next = node;
19+
node.next = next;
20+
node.prev = this;
21+
next.prev = node;
22+
};
23+
/**
24+
* @constructor
25+
*/
26+
var LRUCache = function(capacity) {
27+
this.head = new Node();
28+
this.tail = new Node();
29+
this.head.next = this.tail;
30+
this.tail.prev = this.head;
31+
this.m = {};
32+
this.size = 0;
33+
this.capacity = capacity;
34+
};
35+
36+
/**
37+
* @param {number} key
38+
* @returns {number}
39+
*/
40+
LRUCache.prototype.get = function(key) {
41+
if (this.m[key]) {
42+
this.lift(this.m[key]);
43+
return this.m[key].v;
44+
} else {
45+
return -1;
46+
}
47+
};
48+
49+
LRUCache.prototype.lift = function (node) {
50+
node.remove();
51+
this.head.insertAfter(node);
52+
};
53+
54+
/**
55+
* @param {number} key
56+
* @param {number} value
57+
* @returns {void}
58+
*/
59+
LRUCache.prototype.set = function(key, value) {
60+
var node;
61+
if (this.m[key]) {
62+
node = this.m[key];
63+
this.lift(node);
64+
node.v = value;
65+
} else {
66+
if (this.size === this.capacity) {
67+
var r = this.tail.prev;
68+
delete this.m[r.k];
69+
r.remove();
70+
this.size--;
71+
}
72+
node = new Node(key, value);
73+
this.head.insertAfter(node);
74+
this.m[key] = node;
75+
this.size++;
76+
}
77+
};
78+
79+
if (DEBUG) {
80+
var cache = new LRUCache(1);
81+
cache.set(2, 1);
82+
console.log(cache.get(2));
83+
cache.set(2, 3);
84+
console.log(cache.get(2));
85+
cache.set(4, 3);
86+
console.log(cache.get(2));
87+
console.log(cache.get(4));
88+
}

0 commit comments

Comments
 (0)