-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
69 lines (61 loc) · 1.54 KB
/
index.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
/**
* LRU Cache implementation
*
* @param {Number} [limit] - 120
*/
module.exports = class LRUCache {
limit = 120;
map = new Map();
constructor(limit) {
if (limit !== undefined) {
this.limit = limit
}
}
/**
* Delete a key-value pair if exists
*
* @param {any} key
* @returns {null}
*/
delete(key) {
if (this.map.has(key) === true) {
this.map.delete(key)
return;
} else {
throw Error("you little bastard");
}
}
/**
*
* @param {any} key
* @returns {null|any}
*/
get(key) {
let value = this.map.get(key)
if (!value) {
return null;
}
this.delete(key) // refreshing in-order to push the key-value pair to the end
this.insert(key, value)
return value;
}
/**
* Insert a key-value pair, if the pair already exists update them
*
* @param {any} key
* @param {any} value
* @returns {Map<any, any>}
*/
insert(key, value) {
if (this.map.size >= this.limit) {
let first = this.map.keys().next().value;
this.delete(first)
if (this.map.has(key) === true) {
this.delete(key) // refreshing to push the pair at the end
return this.map.set(key, value);
}
return this.map.set(key, value)
}
return this.map.set(key, value)
}
}