Last active
December 21, 2020 17:28
-
-
Save jonasgeiler/36ffe95482605ac26723fb97d7c7897c to your computer and use it in GitHub Desktop.
Simple in-memory cache implementation for JavaScript
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
/** | |
* @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