forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.js
More file actions
Latest commit
146 lines (118 loc) · 2.69 KB
/
Copy pathLRUCache.js
File metadata and controls
146 lines (118 loc) · 2.69 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
classLRUCache{
// LRU Cache to store a given capacity of data
#capacity
/**
* @param {number} capacity - the capacity of LRUCache
* @returns {LRUCache} - sealed
*/
constructor(capacity){
if(!Number.isInteger(capacity)||capacity<0){
thrownewTypeError('Invalid capacity')
}
this.#capacity =~~capacity
this.misses=0
this.hits=0
this.cache=newMap()
returnObject.seal(this)
}
getinfo(){
returnObject.freeze({
misses: this.misses,
hits: this.hits,
capacity: this.capacity,
size: this.size
})
}
getsize(){
returnthis.cache.size
}
getcapacity(){
returnthis.#capacity
}
setcapacity(newCapacity){
if(newCapacity<0){
thrownewRangeError('Capacity should be greater than 0')
}
if(newCapacity<this.capacity){
letdiff=this.capacity-newCapacity
while(diff--){
this.#removeLeastRecentlyUsed()
}
}
this.#capacity =newCapacity
}
/**
* delete oldest key existing in map by the help of iterator
*/
#removeLeastRecentlyUsed(){
this.cache.delete(this.cache.keys().next().value)
}
/**
* @param {string} key
* @returns {*}
*/
has(key){
key=String(key)
returnthis.cache.has(key)
}
/**
* @param {string} key
* @param {*} value
*/
set(key,value){
key=String(key)
// Sets the value for the input key and if the key exists it updates the existing key
if(this.size===this.capacity){
this.#removeLeastRecentlyUsed()
}
this.cache.set(key,value)
}
/**
* @param {string} key
* @returns {*}
*/
get(key){
key=String(key)
// Returns the value for the input key. Returns null if key is not present in cache
if(this.cache.has(key)){
constvalue=this.cache.get(key)
// refresh the cache to update the order of key
this.cache.delete(key)
this.cache.set(key,value)
this.hits++
returnvalue
}
this.misses++
returnnull
}
/**
* @param {JSON} json
* @returns {LRUCache}
*/
parse(json){
const{ misses, hits, cache }=JSON.parse(json)
this.misses+=misses??0
this.hits+=hits??0
for(constkeyincache){
this.set(key,cache[key])
}
returnthis
}
/**
* @param {number} indent
* @returns {JSON} - string
*/
toString(indent){
constreplacer=(_,value)=>{
if(valueinstanceofSet){
return[...value]
}
if(valueinstanceofMap){
returnObject.fromEntries(value)
}
returnvalue
}
returnJSON.stringify(this,replacer,indent)
}
}
exportdefaultLRUCache