Last active
April 1, 2021 15:21
-
-
Save ha6000/84635acc8fb22eec81aade198e1edb62 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Harry Kruger | |
// License: MIT | |
class LimitedSet extends Set { | |
constructor(limit = 0, maxAge = 0, sweepInterval = 1000 * 60, init) { | |
super(init); | |
this.limit = limit; | |
this.maxAge = maxAge; | |
this._sweepInterval = sweepInterval; | |
this._creationDates = new Map(); | |
if (this.maxAge && this.sweepInterval) this._createInterval(this.sweepInterval); | |
} | |
set sweepInterval(val) { | |
this._updateInterval(val); | |
this._sweepInterval = val; | |
} | |
get sweepInterval() { | |
return this._sweepInterval; | |
} | |
_createInterval(sweepInterval) { | |
this.interval = setInterval(this._sweep.bind(this), sweepInterval); | |
} | |
_updateInterval(sweepInterval) { | |
if (this.interval) { | |
this._clearInterval(this.interval); | |
this._createInterval(sweepInterval); | |
} | |
} | |
_clearInterval(interval) { | |
clearInterval(interval); | |
} | |
_sweep() { | |
for (let value of this.values()) { | |
// check if date is older then maxAge | |
if (this._creationDates.get(value) + this.maxAge < Date.now()) this.delete(value); | |
} | |
} | |
add(value) { | |
// ensure correct limit | |
if (this.size && this.limit && this.size >= this.limit) this.delete(this.values().next().value); | |
this._creationDates.set(value, Date.now()); | |
super.add(value); | |
} | |
delete(value) { | |
this._creationDates.delete(value); | |
super.delete(value); | |
} | |
destroy() { | |
this._clearInterval(this.interval); | |
} | |
} | |
module.exports = LimitedSet; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment