Skip to content

Instantly share code, notes, and snippets.

@AaronHarris
Created August 23, 2017 18:22
Show Gist options
  • Save AaronHarris/67175dde43282b001660d11cbc1d7614 to your computer and use it in GitHub Desktop.
Save AaronHarris/67175dde43282b001660d11cbc1d7614 to your computer and use it in GitHub Desktop.
A TimeCache is a subclass of Map where keys become invalidated after a certain amount of time
DEFAULT_CACHE_TIME_MS = 262144; // ~5 minutes (closest 1-bin value)
export default class TimeCache extends Map {
constructor(cacheTime, seed) {
super(seed);
this.cacheTime = cacheTime || DEFAULT_CACHE_TIME_MS;
}
set(key, value, cacheTime) {
super.set(key, {
expires: Date.now() + (cacheTime || this.cacheTime),
data: value
});
}
get(key) {
var entry = super.get(key);
if (entry && Date.now() < entry.expires) {
return entry.data;
} else if (entry) {
super.delete(key);
}
}
has(key) {
if (super.has(key)) {
var entry = super.get(key);
if (entry && Date.now() < entry.expires) {
return super.has(key);
} else if (entry) {
super.delete(key);
}
}
return false;
}
static get [Symbol.species]() { return Map; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment