@@ -93,15 +93,19 @@ export class BasicCache {
93
93
}
94
94
}
95
95
96
+ const DEFAULT_LRU_LIMIT = 1000
97
+ const DEFAULT_LRU_EVICT_COUNT = 1
98
+
96
99
/**
97
100
* Implements caching strategy that evicts least-recently-used items in cache
98
101
* when an item is being added to a cache that has reached a configured size
99
102
* limit.
100
103
*/
101
104
export class LRUCache {
102
105
103
- constructor ( limit = 1000 , cache = new BasicCache ( ) , lru = OrderedSet ( ) ) {
106
+ constructor ( limit = DEFAULT_LRU_LIMIT , evictCount = DEFAULT_LRU_EVICT_COUNT , cache = new BasicCache ( ) , lru = OrderedSet ( ) ) {
104
107
this . limit = limit ;
108
+ this . evictCount = evictCount
105
109
this . cache = cache ;
106
110
this . lru = lru ;
107
111
}
@@ -145,7 +149,7 @@ export class LRUCache {
145
149
}
146
150
147
151
// remove it first to reorder in lru OrderedSet
148
- return new LRUCache ( this . limit , this . cache , this . lru . remove ( item ) . add ( item ) )
152
+ return new LRUCache ( this . limit , this . evictCount , this . cache , this . lru . remove ( item ) . add ( item ) )
149
153
}
150
154
151
155
/**
@@ -157,17 +161,30 @@ export class LRUCache {
157
161
*/
158
162
miss ( item , entry ) {
159
163
if ( this . lru . size >= this . limit ) {
160
- // TODO add options to clear multiple items at once
161
- const evictItem = this . has ( item ) ? item : this . lru . first ( )
164
+ if ( this . has ( item ) ) {
165
+ return new LRUCache (
166
+ this . limit ,
167
+ this . evictCount ,
168
+ this . cache . miss ( item , entry ) ,
169
+ this . lru . remove ( item ) . add ( item )
170
+ )
171
+ }
172
+
173
+ const cache = ( this . lru
174
+ . take ( this . evictCount )
175
+ . reduce ( ( c , evictItem ) => c . evict ( evictItem ) , this . cache )
176
+ . miss ( item , entry ) ) ;
162
177
163
178
return new LRUCache (
164
179
this . limit ,
165
- this . cache . evict ( evictItem ) . miss ( item , entry ) ,
166
- this . lru . remove ( evictItem ) . add ( item )
180
+ this . evictCount ,
181
+ cache ,
182
+ this . lru . skip ( this . evictCount ) . add ( item )
167
183
)
168
184
} else {
169
185
return new LRUCache (
170
186
this . limit ,
187
+ this . evictCount ,
171
188
this . cache . miss ( item , entry ) ,
172
189
this . lru . add ( item )
173
190
)
@@ -186,6 +203,7 @@ export class LRUCache {
186
203
187
204
return new LRUCache (
188
205
this . limit ,
206
+ this . evictCount ,
189
207
this . cache . evict ( item ) ,
190
208
this . lru . remove ( item )
191
209
)
0 commit comments