Skip to content

Commit

Permalink
Automatically release memory when an item expires - fixes #14
Browse files Browse the repository at this point in the history
  • Loading branch information
SamVerschueren committed Aug 22, 2018
1 parent 77874ca commit 6c87cf1
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 6 deletions.
11 changes: 6 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
@@ -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();

Expand All @@ -26,18 +27,18 @@ 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);

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);
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"promise"
],
"dependencies": {
"map-age-cleaner": "^0.1.1",
"mimic-fn": "^1.0.0",
"p-is-promise": "^1.1.0"
},
Expand Down
2 changes: 2 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 5 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 6c87cf1

Please sign in to comment.