Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automatically release memory when an item expires - fixes #14 #19

Merged
merged 1 commit into from Aug 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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