Who wants to keep track of what's not being used? This guy!
So I'm writing this other library that needs to do some basic caching, right? You know - the first hard thing. (For an idea of my work on the second hard thing, see the examples below.)
It's not so much that I need flotsam deleted right away when it expires as I want the value to be refreshed every so often, and if that value goes a long enough time with out being accessed, theeeeen I'll drop it.
To lessen the pain in this task, I need a library that will keep track of what the last time was when I accessed something, and alert me if a certain amount of time passes without that thing being touched. So, making the assumption that those "somethings" can be identified by a string, and the assertion that I will need these last-access-times to persist even after reopening the screen or re-launching the process, I wrote this-here code.
// Some levelUP dbvar db = level'wat'// Expire stuff after 15 seconds of inactivityvar expirer = 15000 db// Things are only interesting if they were active in the last 15 secondsvar areTheseThingsInteresting ='thing1': false'thing2': falsevarareTheseThingsInterestingthingKey = true// note that this thing was fiddled withexpirertouchthingKeyexpireron'expire'console.logthingKey + " expired!"areTheseThingsInterestingthingKey = falseactivity'thing1'activity'thing2'setTimeoutactivity'thing1'10 * 1000// thing1 will expire after 25 seconds after the first time it was touched// thing2 will expire 15 seconds after the first time it was touched
The module returns a constructor function:
The resulting object is an EventEmitter with the following functions as properties:
Updates the "last touched" timestamp. Expire events will not fire for a key until at least timeoutMs after the last time the key was touched.
Forgets about a key. Won't fire any expire events for it (unless you touch that key again).
Shuts down any timeouts that are floating around, letting you shut down your server nicely and stuff.