File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ class LRUCache {
2
+ /**
3
+ * @param {number } maxSize maxSize
4
+ */
5
+ constructor ( maxSize ) {
6
+ this . _maxSize = maxSize ;
7
+ /** @type {string[] } */
8
+ this . _doublyQueue = [ ] ;
9
+ this . _cacheMap = new Map ( ) ;
10
+ }
11
+
12
+ /**
13
+ * @param {string } item item
14
+ */
15
+ get ( item ) {
16
+ if ( this . _cacheMap . has ( item ) ) {
17
+ const itemData = this . _doublyQueue . splice (
18
+ this . _doublyQueue . indexOf ( item ) ,
19
+ 1
20
+ ) ;
21
+ this . _doublyQueue . unshift ( item ) ;
22
+
23
+ if ( itemData . length > 0 ) {
24
+ this . _cacheMap . set ( item , itemData [ 0 ] ) ;
25
+ }
26
+ }
27
+ }
28
+
29
+ /**
30
+ * @param {any } item item
31
+ * @param {any } itemData itemData
32
+ */
33
+ set ( item , itemData ) {
34
+ if ( this . _doublyQueue . length === this . _maxSize ) {
35
+ const last = this . _doublyQueue [ this . _doublyQueue . length - 1 ] ;
36
+ this . _doublyQueue . pop ( ) ;
37
+ this . _cacheMap . delete ( last ) ;
38
+ }
39
+
40
+ this . _doublyQueue . unshift ( item ) ;
41
+ this . _cacheMap . set ( item , itemData ) ;
42
+ }
43
+ }
44
+
45
+ module . exports = LRUCache ;
You can’t perform that action at this time.
0 commit comments