2 const mimicFn = require('mimic-fn');
3 const isPromise = require('p-is-promise');
4 const mapAgeCleaner = require('map-age-cleaner');
6 const cacheStore = new WeakMap();
8 const defaultCacheKey = (...arguments_) => {
9 if (arguments_.length === 0) {
10 return '__defaultKey';
13 if (arguments_.length === 1) {
14 const [firstArgument] = arguments_;
16 firstArgument === null ||
17 firstArgument === undefined ||
18 (typeof firstArgument !== 'function' && typeof firstArgument !== 'object')
24 return JSON.stringify(arguments_);
27 const mem = (fn, options) => {
28 options = Object.assign({
29 cacheKey: defaultCacheKey,
31 cachePromiseRejection: false
34 if (typeof options.maxAge === 'number') {
35 mapAgeCleaner(options.cache);
38 const {cache} = options;
39 options.maxAge = options.maxAge || 0;
41 const setData = (key, data) => {
44 maxAge: Date.now() + options.maxAge
48 const memoized = function (...arguments_) {
49 const key = options.cacheKey(...arguments_);
52 return cache.get(key).data;
55 const cacheItem = fn.call(this, ...arguments_);
57 setData(key, cacheItem);
59 if (isPromise(cacheItem) && options.cachePromiseRejection === false) {
60 // Remove rejected promises from cache unless `cachePromiseRejection` is set to `true`
61 cacheItem.catch(() => cache.delete(key));
68 // The below call will throw in some host environments
69 // See https://github.com/sindresorhus/mimic-fn/issues/10
70 mimicFn(memoized, fn);
73 cacheStore.set(memoized, options.cache);
79 // TODO: Remove this for the next major release
80 module.exports.default = mem;
82 module.exports.clear = fn => {
83 const cache = cacheStore.get(fn);
85 if (cache && typeof cache.clear === 'function') {