LFU Cache LeetCode solution in JavaScript

1
/**
2
* @param {number} capacity
3
*/
4
var LFUCache = function (capacity) {
5
this.capacity = capacity;
6
this.cache = [];
7
};
8

9
/**
10
* @param {number} key
11
* @return {number}
12
*/
13
LFUCache.prototype.get = function (key) {
14
let val = -1;
15
if (!this.capacity) return val;
16
const existIndex = this.cache.findIndex((item) => item.key === key);
17
if (existIndex > -1) {
18
const item = this.cache[existIndex];
19
val = item.value;
20
item.count++;
21
this.cache.splice(existIndex, 1);
22
this.cache.unshift(item);
23
}
24
return val;
25
};
26

27
/**
28
* @param {number} key
29
* @param {number} value
30
* @return {void}
31
*/
32
LFUCache.prototype.put = function (key, value) {
33
if (!this.capacity) return;
34
const existIndex = this.cache.findIndex((item) => item.key === key);
35
if (existIndex > -1) {
36
// new item already exists,rewrite the value and increase count
37
const existItem = this.cache[existIndex];
38
existItem.value = value;
39
existItem.count++;
40
this.cache.splice(existIndex, 1);
41
this.cache.unshift(existItem);
42
} else {
43
// new item doesn't exist
44
if (this.cache.length === this.capacity) {
45
// reach the capacity, need to clear LFU
46
let lfuIndex = 0;
47
let leastCount = this.cache[lfuIndex].count;
48
for (let i = 1; i < this.cache.length; i++) {
49
const item = this.cache[i];
50
if (item.count <= leastCount) {
51
leastCount = item.count;
52
lfuIndex = i;
53
}
54
}
55
this.cache.splice(lfuIndex, 1);
56
// after clear LFU, push the new item
57
this.cache.unshift({
58
key,
59
value,
60
count: 1,
61
});
62
} else {
63
// new item can be pushed
64
this.cache.unshift({
65
key,
66
value,
67
count: 1,
68
});
69
}
70
}
71
};
72

73
/**
74
* Your LFUCache object will be instantiated and called as such:
75
* var obj = new LFUCache(capacity)
76
* var param_1 = obj.get(key)
77
* obj.put(key,value)
78
*/

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0