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 27, 2018
1 parent a90ebb8 commit 8b4ccf6
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 7 deletions.
12 changes: 6 additions & 6 deletions 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();

Expand Down Expand Up @@ -30,8 +31,11 @@ module.exports = (fn, options) => {
cachePromiseRejection: false
}, options);

if (typeof options.maxAge === 'number') {
mapAgeCleaner(options.cache);
}

const {cache} = options;
const noMaxAge = typeof options.maxAge !== 'number';
options.maxAge = options.maxAge || 0;

const setData = (key, data) => {
Expand All @@ -47,11 +51,7 @@ module.exports = (fn, options) => {
if (cache.has(key)) {
const c = cache.get(key);

if (noMaxAge || 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
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
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
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 8b4ccf6

Please sign in to comment.