Skip to content

Commit

Permalink
Backport memory leak fixes
Browse files Browse the repository at this point in the history
Commit da4e439 resolved memory
leaking issues by introducing a dependency that was not compatible
with Node.js v4 which mem v1 supported. This commit adds timers
for ensuring the cache Map is cleaned up without using additional
dependencies.

Bug ref: sindresorhus#14
  • Loading branch information
sigv committed Jul 17, 2019
1 parent 36d2861 commit 77edd25
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions index.js
Expand Up @@ -20,20 +20,30 @@ module.exports = (fn, opts) => {
const memoized = function () {
const cache = cacheStore.get(memoized);
const key = opts.cacheKey.apply(null, arguments); // eslint-disable-line prefer-rest-params
const maxAgeDefined = typeof opts.maxAge === 'number';

if (cache.has(key)) {
const c = cache.get(key);

if (typeof opts.maxAge !== 'number' || Date.now() < c.maxAge) {
if (!maxAgeDefined || Date.now() < c.maxAge) {
return c.data;
}

if (typeof c.maxAgeTimeout !== 'undefined') {
clearTimeout(c.maxAgeTimeout);
}

cache.delete(key);
}

const ret = fn.apply(null, arguments); // eslint-disable-line prefer-spread, prefer-rest-params

cache.set(key, {
data: ret,
maxAge: Date.now() + (opts.maxAge || 0)
maxAge: maxAgeDefined ? Date.now() + opts.maxAge : Infinity,
maxAgeTimeout: maxAgeDefined ? setTimeout(() => {
cache.delete(key);
}, opts.maxAge).unref() : undefined
});

return ret;
Expand All @@ -50,6 +60,12 @@ module.exports.clear = fn => {
const cache = cacheStore.get(fn);

if (cache && typeof cache.clear === 'function') {
cache.forEach(c => {
if (typeof c.maxAgeTimeout !== 'undefined') {
clearTimeout(c.maxAgeTimeout);
}
});

cache.clear();
}
};

0 comments on commit 77edd25

Please sign in to comment.