UNPKG

superfly-timeline

Version:

Resolver for defining objects with temporal boolean logic relationships on a timeline

55 lines 1.73 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Cache = void 0; class Cache { constructor(autoCleanup = false) { this.autoCleanup = autoCleanup; this.cache = new Map(); this.clearTimeout = undefined; this.timeToCueNewCleanup = false; if (this.autoCleanup) this.timeToCueNewCleanup = true; } /** Cache the result of function for a limited time */ cacheResult(key, fcn, limitTime) { const cache = this.cache.get(key); if (!cache || cache.ttl < Date.now()) { const value = fcn(); this.cache.set(key, { ttl: Date.now() + limitTime, value: value, }); if (this.timeToCueNewCleanup) { this.timeToCueNewCleanup = false; /* istanbul ignore next */ this.clearTimeout = setTimeout(() => { this.clearTimeout = undefined; this.timeToCueNewCleanup = true; this.cleanUp(); }, limitTime + 100); } return value; } else { return cache.value; } } /* istanbul ignore next */ cleanUp() { const now = Date.now(); for (const [key, value] of this.cache.entries()) { if (value.ttl < now) this.cache.delete(key); } } clear() { this.cache.clear(); if (this.clearTimeout) { clearTimeout(this.clearTimeout); this.clearTimeout = undefined; this.timeToCueNewCleanup = true; } } } exports.Cache = Cache; //# sourceMappingURL=cache.js.map