Last active
October 5, 2017 03:14
-
-
Save maman/557aa2b3b55bc971cf415c0c8369c874 to your computer and use it in GitHub Desktop.
Map implementation with per-record TTL support
This file contains 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
class TTLMap { | |
constructor(TTL) { | |
this.ttl = TTL; | |
this.timeoutData = {}; | |
this.data = new Map(); | |
} | |
_clearTimeout(key) { | |
clearTimeout(this.timeoutData[key]); | |
delete this.timeoutData[key]; | |
} | |
get(key) { | |
return this.data.get(key); | |
} | |
set(key, val) { | |
this.clearTimeout(key); | |
this.data.set(key, val); | |
this.timeoutData[key] = setTimeout(() => { | |
this._clearTimeout(key); | |
this.data.delete(key); | |
this.delete(key); | |
}, this.ttl) | |
return this; | |
} | |
delete(key) { | |
this.clearTimeout(key); | |
if (this.data.has(key)) { | |
this.data.delete(key); | |
return true; | |
} | |
this.data.delete(key); | |
return false; | |
} | |
clear() { | |
this.data = {}; | |
Object.values(this.timeoutData).forEach(t => clearTimeout(t)); | |
this.timeoutData = {}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment