Skip to content

Instantly share code, notes, and snippets.

@adrian154
Created October 15, 2021 01:43
Show Gist options
  • Save adrian154/d0e7ec3a2a9c97f0818ed3d821bb08cc to your computer and use it in GitHub Desktop.
Save adrian154/d0e7ec3a2a9c97f0818ed3d821bb08cc to your computer and use it in GitHub Desktop.
// 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