-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
index.js
78 lines (61 loc) · 1.62 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'use strict';
const mimicFn = require('mimic-fn');
const isPromise = require('p-is-promise');
const mapAgeCleaner = require('map-age-cleaner');
const cacheStore = new WeakMap();
const defaultCacheKey = (...arguments_) => {
if (arguments_.length === 0) {
return '__defaultKey';
}
if (arguments_.length === 1) {
const [firstArgument] = arguments_;
const isObject = typeof firstArgument === 'object' && firstArgument !== null;
const isPrimitive = !isObject;
if (isPrimitive) {
return firstArgument;
}
}
return JSON.stringify(arguments_);
};
const mem = (fn, {
cacheKey = defaultCacheKey,
cache = new Map(),
cachePromiseRejection = true,
maxAge
} = {}) => {
if (typeof maxAge === 'number') {
mapAgeCleaner(cache);
}
const memoized = function (...arguments_) {
const key = cacheKey(...arguments_);
if (cache.has(key)) {
return cache.get(key).data;
}
const cacheItem = fn.apply(this, arguments_);
cache.set(key, {
data: cacheItem,
maxAge: maxAge ? Date.now() + maxAge : Infinity
});
if (isPromise(cacheItem) && cachePromiseRejection === false) {
cacheItem.catch(() => cache.delete(key));
}
return cacheItem;
};
try {
// The below call will throw in some host environments
// See https://github.com/sindresorhus/mimic-fn/issues/10
mimicFn(memoized, fn);
} catch (_) {}
cacheStore.set(memoized, cache);
return memoized;
};
module.exports = mem;
module.exports.clear = fn => {
if (!cacheStore.has(fn)) {
throw new Error('Can\'t clear a function that was not memoized!');
}
const cache = cacheStore.get(fn);
if (typeof cache.clear === 'function') {
cache.clear();
}
};