diff --git a/index.js b/index.js index 5c29152..151f5c9 100644 --- a/index.js +++ b/index.js @@ -1,6 +1,7 @@ 'use strict'; const mimicFn = require('mimic-fn'); const isPromise = require('p-is-promise'); +const mapAgeCleaner = require('map-age-cleaner'); const cacheStore = new WeakMap(); @@ -26,6 +27,10 @@ module.exports = (fn, options) => { cachePromiseRejection: false }, options); + if (typeof options.maxAge === 'number') { + mapAgeCleaner(options.cache); + } + const memoized = function (...args) { const cache = cacheStore.get(memoized); const key = options.cacheKey(...args); @@ -33,11 +38,7 @@ module.exports = (fn, options) => { if (cache.has(key)) { const c = cache.get(key); - if (typeof options.maxAge !== 'number' || Date.now() < c.maxAge) { - return c.data; - } - - cache.delete(key); + return c.data; } const ret = fn.call(this, ...args); diff --git a/package.json b/package.json index 0ace1d7..fd9097b 100644 --- a/package.json +++ b/package.json @@ -32,6 +32,7 @@ "promise" ], "dependencies": { + "map-age-cleaner": "^0.1.1", "mimic-fn": "^1.0.0", "p-is-promise": "^1.1.0" }, diff --git a/readme.md b/readme.md index 72575a7..add4222 100644 --- a/readme.md +++ b/readme.md @@ -2,6 +2,8 @@ > [Memoize](https://en.wikipedia.org/wiki/Memoization) functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input +Memory is automatically released when an item expires. + ## Install diff --git a/test.js b/test.js index 534e789..7c8cf89 100644 --- a/test.js +++ b/test.js @@ -45,7 +45,11 @@ test('maxAge option deletes old items', async t => { const f = () => i++; const cache = new Map(); const deleted = []; - cache.delete = item => deleted.push(item); + const remove = cache.delete.bind(cache); + cache.delete = item => { + deleted.push(item); + return remove(item); + }; const memoized = m(f, {maxAge: 100, cache}); t.is(memoized(1), 0); t.is(memoized(1), 0);