-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
106 lines (81 loc) · 1.62 KB
/
script.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
class Node {
constructor(key,val) {
this.key = key
this.value = val
this.prev = null
this.next = null
}
}
class Cache {
constructor() {
this.limit = 10
this.head = null
this.tail = null
this.length = 0
this.cache = {}
}
setItem(key, val) {
if(this.getItem(key)) return false
this.checkLimit()
let node = new Node(key, val)
if (!this.head) {
this.head = node
this.tail = node
} else {
let temp = this.head
this.head = node
node.next = temp
temp.prev = node
}
this.cache[key] = this.head;
this.length++
return true
}
getItem(key) {
if(this.cache[key]){
let value = this.cache[key].value;
this.removeItem(key)
this.setItem(key, value);
return value;
}
return false
}
checkLimit(){
if(this.length === this.limit){
this.removeItem(this.tail.key)
}
}
removeItem(key) {
let node = this.cache[key];
if(node.prev !== null){
node.prev.next = node.next;
} else {
this.head = node.next;
}
if(node.next !== null){
node.next.prev = node.prev;
} else {
this.tail = node.prev
}
delete this.cache[key];
this.length--;
}
getList() {
let arr = []
let current = this.head
let counter = 0
while(counter < this.length) {
arr.push(current.key)
current = current.next
counter++
}
return arr
}
reset() {
this.head = null;
this.tail = null;
this.length = 0;
this.cache = {};
}
}
let MyCache = new Cache;