Skip to content

Commit

Permalink
Cleanup (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante authored and sindresorhus committed Jun 15, 2019
1 parent d88dab7 commit c098182
Showing 1 changed file with 17 additions and 27 deletions.
44 changes: 17 additions & 27 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,41 +22,31 @@ const defaultCacheKey = (...arguments_) => {
return JSON.stringify(arguments_);
};

const mem = (fn, options) => {
options = {
cacheKey: defaultCacheKey,
cache: new Map(),
cachePromiseRejection: true,
...options
};

if (typeof options.maxAge === 'number') {
mapAgeCleaner(options.cache);
const mem = (fn, {
cacheKey = defaultCacheKey,
cache = new Map(),
cachePromiseRejection = true,
maxAge
} = {}) => {
if (typeof maxAge === 'number') {
mapAgeCleaner(cache);
}

const {cache} = options;
options.maxAge = options.maxAge || 0;

const setData = (key, data) => {
cache.set(key, {
data,
maxAge: Date.now() + options.maxAge
});
};

const memoized = function (...arguments_) {
const key = options.cacheKey(...arguments_);
const key = cacheKey(...arguments_);

if (cache.has(key)) {
return cache.get(key).data;
return maxAge ? cache.get(key).data : cache.get(key);
}

const cacheItem = fn.call(this, ...arguments_);
const cacheItem = fn.apply(this, arguments_);

setData(key, cacheItem);
cache.set(key, maxAge ? {
data: cacheItem,
maxAge: Date.now() + maxAge
} : cacheItem);

if (isPromise(cacheItem) && options.cachePromiseRejection === false) {
// Remove rejected promises from cache unless `cachePromiseRejection` is set to `true`
if (isPromise(cacheItem) && cachePromiseRejection === false) {
cacheItem.catch(() => cache.delete(key));
}

Expand All @@ -69,7 +59,7 @@ const mem = (fn, options) => {
mimicFn(memoized, fn);
} catch (_) {}

cacheStore.set(memoized, options.cache);
cacheStore.set(memoized, cache);

return memoized;
};
Expand Down

0 comments on commit c098182

Please sign in to comment.