Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * A cache that stores values for a specifed period of time.
- * TTL = time to live, FYI
- * FYI = for your information, LOL
- * LOL = laughing out loud
- * ME = ridiculous
- */
- class TtlCache {
- constructor() {
- this.hash = {};
- }
- /**
- * @param key {string|number|function|object|null|undefined} the key to hash on
- * @param value the value to store for the given key
- * @param ttl the time to live. how long to keep in the cache. if nothing is passed in, then it will never expire
- * */
- set(key, value, ttl=Number.POSITIVE_INFINITY) {
- this.hash[key] = {
- end : Date.now() + ttl,
- value : value
- };
- }
- /**
- * @return the value for the given key. undefined if its not in the Ttlcache
- * */
- get(key) {
- let hashItem = this.hash[key];
- if (hashItem) {
- if (Date.now() <= hashItem.end) {
- return hashItem.value;
- } else {
- delete this.hash[key]; // cleanup
- }
- }
- return undefined;
- }
- }
- module.exports = TtlCache;
Add Comment
Please, Sign In to add comment