-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlru-cache.js
88 lines (82 loc) · 1.62 KB
/
lru-cache.js
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
var DEBUG = process.env.DEBUG;
function Node(k, v, prev, next) {
this.k = k;
this.v = v;
this.prev = prev;
this.next = next;
}
Node.prototype.remove = function () {
var prev = this.prev;
var next = this.next;
prev.next = next;
next.prev = prev;
};
Node.prototype.insertAfter = function (node) {
var next = this.next;
this.next = node;
node.next = next;
node.prev = this;
next.prev = node;
};
/**
* @constructor
*/
var LRUCache = function(capacity) {
this.head = new Node();
this.tail = new Node();
this.head.next = this.tail;
this.tail.prev = this.head;
this.m = {};
this.size = 0;
this.capacity = capacity;
};
/**
* @param {number} key
* @returns {number}
*/
LRUCache.prototype.get = function(key) {
if (this.m[key]) {
this.lift(this.m[key]);
return this.m[key].v;
} else {
return -1;
}
};
LRUCache.prototype.lift = function (node) {
node.remove();
this.head.insertAfter(node);
};
/**
* @param {number} key
* @param {number} value
* @returns {void}
*/
LRUCache.prototype.set = function(key, value) {
var node;
if (this.m[key]) {
node = this.m[key];
this.lift(node);
node.v = value;
} else {
if (this.size === this.capacity) {
var r = this.tail.prev;
delete this.m[r.k];
r.remove();
this.size--;
}
node = new Node(key, value);
this.head.insertAfter(node);
this.m[key] = node;
this.size++;
}
};
if (DEBUG) {
var cache = new LRUCache(1);
cache.set(2, 1);
console.log(cache.get(2));
cache.set(2, 3);
console.log(cache.get(2));
cache.set(4, 3);
console.log(cache.get(2));
console.log(cache.get(4));
}