From a90ebb8b6c4c73f3ef9059c05ea1d6a6ec4617ee Mon Sep 17 00:00:00 2001 From: Maxwell Gerber Date: Sun, 26 Aug 2018 22:27:57 -0700 Subject: [PATCH] Performance enhancements (#18) --- index.js | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/index.js b/index.js index 5c29152..3d10e37 100644 --- a/index.js +++ b/index.js @@ -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 ( @@ -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; } @@ -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) {