UNPKG

fast-typescript-memoize

Version:

Fast memoization decorator and other helpers with 1st class support for Promises.

36 lines 1.28 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.memoizeExpireUnused = void 0; /** * Similar to lodash.memoize(), but auto-expires the cached results after the * provided number of inactive milliseconds. Each time we read a cached result, * the expiration timer resets. * * This function is more expensive than lodash.memoize(), because it uses a JS * timer under the hood. */ function memoizeExpireUnused(func, { resolver, unusedMs, } = {}) { const cache = new Map(); return function (...args) { var _a, _b; const key = resolver ? resolver.apply(this, args) : args[0]; let slot = cache.get(key); if (!slot) { const result = func.apply(this, args); slot = { result }; cache.set(key, slot); } if (unusedMs) { if (slot.timeout) { clearTimeout(slot.timeout); } slot.timeout = (_b = (_a = setTimeout(removeMapKey.bind(cache, key), unusedMs)).unref) === null || _b === void 0 ? void 0 : _b.call(_a); } return slot.result; }; } exports.memoizeExpireUnused = memoizeExpireUnused; function removeMapKey(key) { this.delete(key); } //# sourceMappingURL=memoizeExpireUnused.js.map