Skip to content

Instantly share code, notes, and snippets.

@maman
Last active October 5, 2017 03:14
Show Gist options
  • Save maman/557aa2b3b55bc971cf415c0c8369c874 to your computer and use it in GitHub Desktop.
Save maman/557aa2b3b55bc971cf415c0c8369c874 to your computer and use it in GitHub Desktop.
Map implementation with per-record TTL support
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