-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcache.js
54 lines (51 loc) · 1.23 KB
/
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
function LRUCache(capacity) {
this.map = {};
this.head = {next: null};
this.tail = {prev: this.head};
this.head.next = this.tail;
this.capacity = capacity;
this.length = 0;
}
LRUCache.prototype = {
get: function (key) {
var item = this.map[key];
if (!item)
return null;
item.unlink();
item.linkTo(this.head);
return item.data;
},
put: function (key, data) {
var item = this.map[key];
if (!item && (this.length === this.capacity)) {
item = this.tail.prev;
delete this.map[item.key];
}
if (item) {
item.unlink();
this.length--;
}
this.map[key] = new CacheItem(key, data, this.head);
this.length++;
}
};
function CacheItem(key, data, prev) {
this.key = key;
this.data = data;
this.linkTo(prev);
}
CacheItem.prototype = {
linkTo: function (prev) {
var next = prev.next;
prev.next = this;
this.prev = prev;
this.next = next;
next.prev = this;
},
unlink: function () {
this.prev.next = this.next;
this.next.prev = this.prev;
this.prev = null;
this.next = null;
}
};