Created
October 15, 2021 01:43
-
-
Save adrian154/d0e7ec3a2a9c97f0818ed3d821bb08cc to your computer and use it in GitHub Desktop.
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
// quick and dirty cache | |
module.exports = class { | |
constructor(maxAge, maxSize) { | |
this.maxAge = maxAge; | |
this.maxSize = maxSize; | |
this.cache = new Map(); | |
} | |
put(key, value) { | |
// shh, don't tell anyone | |
value.__cacheTimestamp = Date.now(); | |
// get rid of duplicates | |
if(this.cache.has(key)) { | |
this.cache.delete(key); | |
} | |
this.cache.set(key, value); | |
// say goodnight :) | |
if(this.cache.size == this.maxSize) { | |
this.cache.delete(this.cache.keys().next().value); | |
} | |
} | |
get(key) { | |
const item = this.cache.get(key); | |
if(item) { | |
// evict entries that are too old | |
if(Date.now() - item.__cacheTimestamp > this.maxAge) { | |
this.cache.delete(key); | |
} else { | |
// refresh order | |
this.cache.delete(key); | |
this.cache.set(key, item); | |
return item; | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment