Skip to content

Commit

Permalink
Slightly improve performance (#57)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante authored May 17, 2020
1 parent 3ffde5d commit ea88c5c
Showing 1 changed file with 8 additions and 7 deletions.
15 changes: 8 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const mapAgeCleaner = require('map-age-cleaner');
const cacheStore = new WeakMap();

const mem = (fn, {
cacheKey = ([firstArgument]) => firstArgument,
cacheKey,
cache = new Map(),
maxAge
} = {}) => {
Expand All @@ -14,20 +14,21 @@ const mem = (fn, {
}

const memoized = function (...arguments_) {
const key = cacheKey(arguments_);
const key = cacheKey ? cacheKey(arguments_) : arguments_[0];

if (cache.has(key)) {
return cache.get(key).data;
const cacheItem = cache.get(key);
if (cacheItem) {
return cacheItem.data;
}

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

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

return cacheItem;
return result;
};

try {
Expand Down

0 comments on commit ea88c5c

Please sign in to comment.