UNPKG

transitory

Version:

In-memory cache with high hit rates via LFU eviction. Supports time-based expiration, automatic loading and metrics.

53 lines 1.49 kB
import { WrappedCache } from '../WrappedCache'; const METRICS = Symbol('metrics'); /** * Extension to a cache that tracks metrics about the size and hit rate of * a cache. */ export class MetricsCache extends WrappedCache { constructor(options) { super(options.parent, options.removalListener || null); this[METRICS] = { hits: 0, misses: 0, get hitRate() { const total = this.hits + this.misses; if (total === 0) return 1.0; return this.hits / total; } }; } /** * Get metrics for this cache. Returns an object with the keys `hits`, * `misses` and `hitRate`. For caches that do not have metrics enabled * trying to access metrics will throw an error. * * @returns * metrics of cache */ get metrics() { return this[METRICS]; } /** * Get the cached value for the specified key if it exists. Will return * the value or `null` if no cached value exist. Updates the usage of the * key. * * @param key - * key to get * @returns * current value or `null` */ getIfPresent(key) { const result = super.getIfPresent(key); if (result === null) { this[METRICS].misses++; } else { this[METRICS].hits++; } return result; } } //# sourceMappingURL=MetricsCache.js.map