Created
August 23, 2017 18:22
-
-
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
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
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