UNPKG

transitory

Version:

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

79 lines 2.79 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.MetricsCache = void 0; var WrappedCache_1 = require("../WrappedCache"); var METRICS = Symbol('metrics'); /** * Extension to a cache that tracks metrics about the size and hit rate of * a cache. */ var MetricsCache = /** @class */ (function (_super) { __extends(MetricsCache, _super); function MetricsCache(options) { var _this = _super.call(this, options.parent, options.removalListener || null) || this; _this[METRICS] = { hits: 0, misses: 0, get hitRate() { var total = this.hits + this.misses; if (total === 0) return 1.0; return this.hits / total; } }; return _this; } Object.defineProperty(MetricsCache.prototype, "metrics", { /** * 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: function () { return this[METRICS]; }, enumerable: false, configurable: true }); /** * 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` */ MetricsCache.prototype.getIfPresent = function (key) { var result = _super.prototype.getIfPresent.call(this, key); if (result === null) { this[METRICS].misses++; } else { this[METRICS].hits++; } return result; }; return MetricsCache; }(WrappedCache_1.WrappedCache)); exports.MetricsCache = MetricsCache; //# sourceMappingURL=MetricsCache.js.map