UNPKG

@dr.pogodin/react-utils

Version:

Collection of generic ReactJS components and utils

54 lines (52 loc) 1.34 kB
/** * Implements the static cache. */ export default class Cache { items = {}; size = 0; constructor(maxSize) { this.maxSize = maxSize; } /** * Cache lookup. * @param key Item key to look for. * @param [maxage=Number.MAX_VALUE] Optional. The maximum age of * cached item to serve. Default to infinite. * @returns Cached item, or null if the item is absent in cache, * or stale. */ get({ key, maxage = Number.MAX_VALUE }) { const item = this.items[key]; return item && Date.now() - item.timestamp < maxage ? item.data : null; } /** * Adds item to cache. * @param data Item to add. * @param key Key to store the item at. * @param size Byte size of the item. */ add(data, key, size) { const cached = this.items[key]; if (cached) this.size -= cached.size; this.items[key] = { data, size, timestamp: Date.now() }; this.size += size; if (this.size > this.maxSize) { const entries = Object.entries(this.items); entries.sort((a, b) => a[1].timestamp - b[1].timestamp); for (const entry of entries) { const [itemKey, item] = entry; delete this.items[itemKey]; this.size -= item.size; if (this.size < this.maxSize / 2) break; } } } } //# sourceMappingURL=Cache.js.map