Skip to content

Instantly share code, notes, and snippets.

@jonasgeiler
Last active December 21, 2020 17:28
Show Gist options
  • Save jonasgeiler/36ffe95482605ac26723fb97d7c7897c to your computer and use it in GitHub Desktop.
Save jonasgeiler/36ffe95482605ac26723fb97d7c7897c to your computer and use it in GitHub Desktop.
Simple in-memory cache implementation for JavaScript
/**
* @typedef CacheOptions
* @type {object}
* @property {number | undefined} maxSize
* @property {number | undefined} maxAge Max Age in Minutes
* @property {any[] | undefined} entries
*/
class Cache extends Map {
/**
* @param {CacheOptions} options
*/
constructor({ maxSize, maxAge, entries }) {
super(entries);
this.maxSize = maxSize;
this.maxAge = maxAge;
}
deleteOldestEntry() {
let keyOfOldestItem, dateOfOldestItem;
super.forEach(({ date }, key) => {
if (!dateOfOldestItem || dateOfOldestItem > date) {
dateOfOldestItem = date;
keyOfOldestItem = key;
}
});
if (keyOfOldestItem) {
super.delete(keyOfOldestItem);
}
}
/**
* @param key
* @param value
* @return {Cache}
*/
set(key, value) {
if (!super.has(key) && this.maxSize && super.size >= this.maxSize) {
this.deleteOldestEntry();
}
super.set(key, {
value,
date: new Date(),
});
return this;
}
/**
* @param key
* @return {undefined | any}
*/
get(key) {
return this.has(key) ? super.get(key).value : undefined;
}
/**
* @param key
* @return {boolean}
*/
has(key) {
if (super.has(key)) {
const entry = super.get(key);
const age = Math.round((new Date() - entry.date) / 60000);
if (this.maxAge && this.maxAge <= age) {
super.delete(key);
return false;
}
return true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment