Skip to content

Commit

Permalink
Add option to periodically clear kept objects and run finalization, k…
Browse files Browse the repository at this point in the history
  • Loading branch information
kriszyp committed Jan 28, 2022
1 parent f8e2c97 commit 9b261b7
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ export class WeakLRUCache extends Map {
if (options && options.cacheSize) {
options.lruSize = options.cacheSize >> 2
}
if (options && options.clearKeptInterval) {
this.clearKeptInterval = options.clearKeptInterval
this.clearKeptCount = 0
this.clearKeptObjects = options.clearKeptObjects
}
this.expirer = (options ? options.expirer === false ? defaultNoLRUExpirer : options.expirer : null) || defaultExpirer || (defaultExpirer = new LRFUExpirer(options))
this.deferRegister = Boolean(options && options.deferRegister)
let registry = this.registry = new FinalizationRegistry(key => {
Expand Down Expand Up @@ -42,6 +47,8 @@ export class WeakLRUCache extends Map {
super.delete(key)
else {
entry.value = value
if (this.clearKeptInterval)
this.incrementClearKeptCount()
if (mode !== 1)
this.expirer.used(entry)
return mode === 2 ? value : entry
Expand All @@ -63,6 +70,8 @@ export class WeakLRUCache extends Map {
let entry
if (value && typeof value == 'object') {
entry = new WeakRef(value)
if (this.clearKeptInterval)
this.incrementClearKeptCount()
entry.value = value
if (this.deferRegister) {
entry.key = key
Expand All @@ -75,6 +84,15 @@ export class WeakLRUCache extends Map {
this.set(key, entry, expirationPriority)
return entry
}
incrementClearKeptCount() {
if (++this.clearKeptCount >= this.clearKeptInterval) {
this.clearKeptCount = 0
if (this.clearKeptObjects)
this.clearKeptObjects()
if (this.registry.cleanupSome)
this.registry.cleanupSome()
}
}
set(key, entry, expirationPriority) {
let oldEntry = super.get(key)
if (oldEntry)
Expand Down

0 comments on commit 9b261b7

Please sign in to comment.