Skip to content

Commit

Permalink
Delete cache entries older than max age (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
keithamus authored and sindresorhus committed Jun 20, 2018
1 parent 74439cc commit cd6320a
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
2 changes: 2 additions & 0 deletions index.js
Expand Up @@ -29,6 +29,8 @@ module.exports = (fn, opts) => {
if (typeof opts.maxAge !== 'number' || Date.now() < c.maxAge) {
return c.data;
}

cache.delete(key);
}

const ret = fn.apply(this, arguments);
Expand Down
39 changes: 39 additions & 0 deletions test.js
Expand Up @@ -40,6 +40,45 @@ test('maxAge option', async t => {
t.is(memoized(1), 1);
});

test('maxAge option deletes old items', async t => {
let i = 0;
const f = () => i++;
const cache = new Map();
const deleted = [];
cache.delete = item => deleted.push(item);
const memoized = m(f, {maxAge: 100, cache});
t.is(memoized(1), 0);
t.is(memoized(1), 0);
t.is(cache.has(1), true);
await delay(50);
t.is(memoized(1), 0);
t.is(deleted.length, 0);
await delay(200);
t.is(memoized(1), 1);
t.is(deleted.length, 1);
t.is(deleted[0], 1);
});

test('maxAge items are deleted even if function throws', async t => {
let i = 0;
const f = () => {
if (i === 1) {
throw new Error('failure');
}
return i++;
};
const cache = new Map();
const memoized = m(f, {maxAge: 100, cache});
t.is(memoized(1), 0);
t.is(memoized(1), 0);
t.is(cache.size, 1);
await delay(50);
t.is(memoized(1), 0);
await delay(200);
t.throws(() => memoized(1), 'failure');
t.is(cache.size, 0);
});

test('cacheKey option', t => {
let i = 0;
const f = () => i++;
Expand Down

0 comments on commit cd6320a

Please sign in to comment.