Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 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 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
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