UNPKG

timed-memoize

Version:
61 lines 2.22 kB
function simple(args) { return args.toString(); } function argsNotEquals(args1, args2) { return args1.some((arg, index) => arg !== args2[index]); } function memoized(fn, cache, cleanup, options) { const { timeout = 0, hot = true, discardUndefined = false, resolver = simple, one = false } = options; const actualResolver = one ? () => 'key' : resolver; let lastArgs = undefined; return function (...args) { const key = actualResolver(args); function cleanupCallback() { lastArgs = undefined; delete cache[key]; delete cleanup[key]; } if (!(key in cache) || one && (lastArgs === undefined || argsNotEquals(args, lastArgs))) { const returnValue = fn.apply(null, arguments); if (!discardUndefined || typeof returnValue !== 'undefined') { cache[key] = returnValue; if (timeout >= 0) { cleanup[key] = setTimeout(cleanupCallback, timeout); } } } else if (hot) { const oldCleanupCallback = cleanup[key]; if (oldCleanupCallback !== undefined) { clearTimeout(oldCleanupCallback); } if (timeout >= 0) { cleanup[key] = setTimeout(cleanupCallback, timeout); } } lastArgs = args; return cache[key]; }; } function timedMemoize(a, b) { if (typeof a === 'function') { // Memoized function value const fn = a; const options = b || {}; const cache = {}; const cleanup = {}; return memoized(fn, cache, cleanup, options); } else if (typeof a === 'object' || arguments.length === 0) { // Memoized key-value pairs const options = a || {}; const cache = {}; const cleanup = {}; return memoized((x, y) => y, cache, cleanup, Object.assign({}, options, { resolver: (args) => args[0].toString(), discardUndefined: true })); } else { throw new Error('Invalid arguments'); } } export default timedMemoize; //# sourceMappingURL=index.js.map