UNPKG

@publidata/utils-fontawesome

Version:
75 lines (66 loc) 2.05 kB
/** * A simple in-memory cache * Inspired by: https://dev.to/seanwelshbrown/implement-a-simple-lru-cache-in-javascript-4o92 * @class MemoryCache * @param {Number} capacity - the maximum number of items to store in the cache * @method get - get the value of a key * @method put - set a key value pair in the cache * @method reset - clear the cache */ class MemoryCache { constructor(_capacity) { this._cache = new Map(); this.capacity = _capacity; } /** * Get the value of a key * @param {String} key * @returns {Object} whatever is stored in the cache */ get(key) { let val = this._cache.get(key); return val; } /** * Set a key value pair in the cache * @param {String} key * @param {Object} value * @returns {void} * @throws {Error} if the key is not a string */ put(key, value) { if (typeof key !== "string") throw new Error("Key must be a string"); // Start by deleting the key if it already exists this._cache.delete(key); if (this._cache.size === this.capacity) { // Delete the first key in the cache with the oldest value this._cache.delete(this._cache.keys().next().value); this._cache.set(key, value); } else { this._cache.set(key, value); } } /** * Set multiple key value pairs in the cache * @param {Array<Object>} keyValues - an array of objects with key and value properties * @returns {void} * @throws {Error} if the key is not a string * @throws {Error} if the keyValues array is longer than the capacity of the cache */ putAll(keyValues) { if (!Array.isArray(keyValues)) throw new Error("keyValues must be an array"); // In case the array is longer than the capacity if (keyValues.length > this.capacity) throw new Error("keyValues is longer than the capacity of the cache"); keyValues.forEach((kv) => this.put(kv.key, kv.value)); } /** * Clear the cache * @returns {void} */ reset() { this._cache.clear(); } } module.exports = MemoryCache;