-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathLRU.js
76 lines (60 loc) · 1.53 KB
/
LRU.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
/**
* LRU( Least recently used )
*/
import DoubleLinkedList from './DoubleLinkedList';
const LIMIT = 20;
export default class LRUCache {
constructor(sqList, limit = LIMIT){
this.limit = limit;
sqList = (sqList && sqList.length) ? sqList && sqList.slice(0, this.limit) : [];
this.__cache = new DoubleLinkedList(sqList, function(a, b){
return a.key === b.key;
});
}
[Symbol.iterator](){
return this.__cache[Symbol.iterator]();
}
get size(){
return this.__cache.size;
}
remove(key){
return this.__cache.remove({ key });
}
clear(){
return this.___cache.clear();
}
get(key){
let index = this.__cache.indexOf({ key });
if(index >= 0) {
let data = this.__cache.findByIndex(index);
this.__cache.remove(data);
this.__cache.unshift(data);
return data;
}
return false;
}
add(key, value){
let data = this.get(key);
if(data) {
data.value = value;
} else {
if(this.size === this.limit) {
this.__cache.pop();
}
this.__cache.unshift({
key,
value
});
}
}
toString(){
let arr = [];
this.__cache.forEach(function(data){
arr.push(`${ data.key }:${ data.value }`);
});
return arr.join(' > ');
}
toJSON(){
return this.__cache.toJSON();
}
}