Skip to content
Permalink
Browse files

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

  • Loading branch information...
SamVerschueren authored and sindresorhus committed Aug 27, 2018
1 parent a90ebb8 commit da4e4398cb27b602de3bd55f746efa9b4a31702b
Showing with 14 additions and 7 deletions.
  1. +6 −6 index.js
  2. +1 −0 package.json
  3. +2 −0 readme.md
  4. +5 −1 test.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();

@@ -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) => {
@@ -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);
@@ -32,6 +32,7 @@
"promise"
],
"dependencies": {
"map-age-cleaner": "^0.1.1",
"mimic-fn": "^1.0.0",
"p-is-promise": "^1.1.0"
},
@@ -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

@@ -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);

0 comments on commit da4e439

Please sign in to comment.
You can’t perform that action at this time.