@@ -13,38 +13,40 @@ class WeakLRUCache {
13
13
constructor ( maxSize ) {
14
14
this . maxSize = maxSize ;
15
15
this . cache = new Map ( ) ;
16
- this . keyMap = new WeakMap ( ) ;
16
+ this . keyMap = new Map ( ) ;
17
17
}
18
18
19
19
get ( key ) {
20
- const keyObj = this . keyMap . get ( key ) ;
21
- if ( ! keyObj ) return undefined ;
22
- const value = this . cache . get ( keyObj ) ;
20
+ const keyString = this . getKeyString ( key ) ;
21
+ const value = this . cache . get ( keyString ) ;
23
22
if ( value ) {
24
- this . cache . delete ( keyObj ) ;
25
- this . cache . set ( keyObj , value ) ;
23
+ this . cache . delete ( keyString ) ;
24
+ this . cache . set ( keyString , value ) ;
26
25
}
27
26
return value ;
28
27
}
29
28
30
29
set ( key , value ) {
31
- let keyObj = this . keyMap . get ( key ) ;
32
- if ( ! keyObj ) {
33
- keyObj = { key } ;
34
- this . keyMap . set ( key , keyObj ) ;
35
- }
36
- if ( this . cache . has ( keyObj ) ) {
37
- this . cache . delete ( keyObj ) ;
30
+ const keyString = this . getKeyString ( key ) ;
31
+ if ( this . cache . has ( keyString ) ) {
32
+ this . cache . delete ( keyString ) ;
38
33
} else if ( this . cache . size >= this . maxSize ) {
39
34
const oldestKey = this . cache . keys ( ) . next ( ) . value ;
40
35
this . cache . delete ( oldestKey ) ;
41
36
}
42
- this . cache . set ( keyObj , value ) ;
37
+ this . cache . set ( keyString , value ) ;
38
+ this . keyMap . set ( keyString , key ) ;
43
39
}
44
40
45
41
clear ( ) {
46
42
this . cache . clear ( ) ;
47
- this . keyMap = new WeakMap ( ) ;
43
+ this . keyMap . clear ( ) ;
44
+ }
45
+
46
+ getKeyString ( key ) {
47
+ return typeof key === 'object' ?
48
+ JSON . stringify ( key ) :
49
+ String ( key ) ;
48
50
}
49
51
}
50
52
0 commit comments