Skip to content

Commit

Permalink
Performance enhancements (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
maxwellgerber authored and sindresorhus committed Aug 27, 2018
1 parent 77874ca commit a90ebb8
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions index.js
Expand Up @@ -5,6 +5,10 @@ const isPromise = require('p-is-promise');
const cacheStore = new WeakMap();

const defaultCacheKey = (...args) => {
if (args.length === 0) {
return '__defaultKey';
}

if (args.length === 1) {
const [firstArgument] = args;
if (
Expand All @@ -26,14 +30,24 @@ module.exports = (fn, options) => {
cachePromiseRejection: false
}, options);

const {cache} = options;
const noMaxAge = typeof options.maxAge !== 'number';
options.maxAge = options.maxAge || 0;

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

const memoized = function (...args) {
const cache = cacheStore.get(memoized);
const key = options.cacheKey(...args);

if (cache.has(key)) {
const c = cache.get(key);

if (typeof options.maxAge !== 'number' || Date.now() < c.maxAge) {
if (noMaxAge || Date.now() < c.maxAge) {
return c.data;
}

Expand All @@ -42,13 +56,6 @@ module.exports = (fn, options) => {

const ret = fn.call(this, ...args);

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

setData(key, ret);

if (isPromise(ret) && options.cachePromiseRejection === false) {
Expand Down

0 comments on commit a90ebb8

Please sign in to comment.