@common.js/p-memoize 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # @common.js/p-memoize
2
+
3
+ The [p-memoize](https://www.npmjs.com/package/p-memoize) package exported as CommonJS modules.
4
+
5
+ Exported from [p-memoize@7.1.0](https://www.npmjs.com/package/p-memoize/v/7.1.0) using https://github.com/etienne-martin/common.js.
@@ -0,0 +1,106 @@
1
+ import type { AsyncReturnType } from 'type-fest';
2
+ export declare type AnyAsyncFunction = (...arguments_: readonly any[]) => Promise<unknown | void>;
3
+ export interface CacheStorage<KeyType, ValueType> {
4
+ has: (key: KeyType) => Promise<boolean> | boolean;
5
+ get: (key: KeyType) => Promise<ValueType | undefined> | ValueType | undefined;
6
+ set: (key: KeyType, value: ValueType) => Promise<unknown> | unknown;
7
+ delete: (key: KeyType) => unknown;
8
+ clear?: () => unknown;
9
+ }
10
+ export interface Options<FunctionToMemoize extends AnyAsyncFunction, CacheKeyType> {
11
+ /**
12
+ Determines the cache key for storing the result based on the function arguments. By default, __only the first argument is considered__ and it only works with [primitives](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
13
+
14
+ A `cacheKey` function can return any type supported by `Map` (or whatever structure you use in the `cache` option).
15
+
16
+ You can have it cache **all** the arguments by value with `JSON.stringify`, if they are compatible:
17
+
18
+ ```
19
+ import pMemoize from 'p-memoize';
20
+
21
+ pMemoize(function_, {cacheKey: JSON.stringify});
22
+ ```
23
+
24
+ Or you can use a more full-featured serializer like [serialize-javascript](https://github.com/yahoo/serialize-javascript) to add support for `RegExp`, `Date` and so on.
25
+
26
+ ```
27
+ import pMemoize from 'p-memoize';
28
+ import serializeJavascript from 'serialize-javascript';
29
+
30
+ pMemoize(function_, {cacheKey: serializeJavascript});
31
+ ```
32
+
33
+ @default arguments_ => arguments_[0]
34
+ @example arguments_ => JSON.stringify(arguments_)
35
+ */
36
+ readonly cacheKey?: (arguments_: Parameters<FunctionToMemoize>) => CacheKeyType;
37
+ /**
38
+ Use a different cache storage. Must implement the following methods: `.has(key)`, `.get(key)`, `.set(key, value)`, `.delete(key)`, and optionally `.clear()`. You could for example use a `WeakMap` instead or [`quick-lru`](https://github.com/sindresorhus/quick-lru) for a LRU cache. To disable caching so that only concurrent executions resolve with the same value, pass `false`.
39
+
40
+ @default new Map()
41
+ @example new WeakMap()
42
+ */
43
+ readonly cache?: CacheStorage<CacheKeyType, AsyncReturnType<FunctionToMemoize>> | false;
44
+ }
45
+ /**
46
+ [Memoize](https://en.wikipedia.org/wiki/Memoization) functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input.
47
+
48
+ @param fn - Function to be memoized.
49
+
50
+ @example
51
+ ```
52
+ import {setTimeout as delay} from 'node:timer/promises';
53
+ import pMemoize from 'p-memoize';
54
+ import got from 'got';
55
+
56
+ const memoizedGot = pMemoize(got);
57
+
58
+ await memoizedGot('https://sindresorhus.com');
59
+
60
+ // This call is cached
61
+ await memoizedGot('https://sindresorhus.com');
62
+
63
+ await delay(2000);
64
+
65
+ // This call is not cached as the cache has expired
66
+ await memoizedGot('https://sindresorhus.com');
67
+ ```
68
+ */
69
+ export default function pMemoize<FunctionToMemoize extends AnyAsyncFunction, CacheKeyType>(fn: FunctionToMemoize, { cacheKey, cache, }?: Options<FunctionToMemoize, CacheKeyType>): FunctionToMemoize;
70
+ /**
71
+ - Only class methods and getters/setters can be memoized, not regular functions (they aren't part of the proposal);
72
+ - Only [TypeScript’s decorators](https://www.typescriptlang.org/docs/handbook/decorators.html#parameter-decorators) are supported, not [Babel’s](https://babeljs.io/docs/en/babel-plugin-proposal-decorators), which use a different version of the proposal;
73
+ - Being an experimental feature, they need to be enabled with `--experimentalDecorators`; follow TypeScript’s docs.
74
+
75
+ @returns A [decorator](https://github.com/tc39/proposal-decorators) to memoize class methods or static class methods.
76
+
77
+ @example
78
+ ```
79
+ import {pMemoizeDecorator} from 'p-memoize';
80
+
81
+ class Example {
82
+ index = 0
83
+
84
+ @pMemoizeDecorator()
85
+ async counter() {
86
+ return ++this.index;
87
+ }
88
+ }
89
+
90
+ class ExampleWithOptions {
91
+ index = 0
92
+
93
+ @pMemoizeDecorator()
94
+ async counter() {
95
+ return ++this.index;
96
+ }
97
+ }
98
+ ```
99
+ */
100
+ export declare function pMemoizeDecorator<FunctionToMemoize extends AnyAsyncFunction, CacheKeyType>(options?: Options<FunctionToMemoize, CacheKeyType>): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => void;
101
+ /**
102
+ Clear all cached data of a memoized function.
103
+
104
+ @param fn - Memoized function.
105
+ */
106
+ export declare function pMemoizeClear(fn: AnyAsyncFunction): void;
package/dist/index.js ADDED
@@ -0,0 +1,370 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ /**
13
+ [Memoize](https://en.wikipedia.org/wiki/Memoization) functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input.
14
+
15
+ @param fn - Function to be memoized.
16
+
17
+ @example
18
+ ```
19
+ import {setTimeout as delay} from 'node:timer/promises';
20
+ import pMemoize from 'p-memoize';
21
+ import got from 'got';
22
+
23
+ const memoizedGot = pMemoize(got);
24
+
25
+ await memoizedGot('https://sindresorhus.com');
26
+
27
+ // This call is cached
28
+ await memoizedGot('https://sindresorhus.com');
29
+
30
+ await delay(2000);
31
+
32
+ // This call is not cached as the cache has expired
33
+ await memoizedGot('https://sindresorhus.com');
34
+ ```
35
+ */ default: function() {
36
+ return pMemoize;
37
+ },
38
+ pMemoizeDecorator: function() {
39
+ return pMemoizeDecorator;
40
+ },
41
+ pMemoizeClear: function() {
42
+ return pMemoizeClear;
43
+ }
44
+ });
45
+ var _mimicFn = /*#__PURE__*/ _interopRequireDefault(require("mimic-fn"));
46
+ function _arrayLikeToArray(arr, len) {
47
+ if (len == null || len > arr.length) len = arr.length;
48
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
49
+ return arr2;
50
+ }
51
+ function _arrayWithHoles(arr) {
52
+ if (Array.isArray(arr)) return arr;
53
+ }
54
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
55
+ try {
56
+ var info = gen[key](arg);
57
+ var value = info.value;
58
+ } catch (error) {
59
+ reject(error);
60
+ return;
61
+ }
62
+ if (info.done) {
63
+ resolve(value);
64
+ } else {
65
+ Promise.resolve(value).then(_next, _throw);
66
+ }
67
+ }
68
+ function _asyncToGenerator(fn) {
69
+ return function() {
70
+ var self = this, args = arguments;
71
+ return new Promise(function(resolve, reject) {
72
+ var gen = fn.apply(self, args);
73
+ function _next(value) {
74
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
75
+ }
76
+ function _throw(err) {
77
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
78
+ }
79
+ _next(undefined);
80
+ });
81
+ };
82
+ }
83
+ function _interopRequireDefault(obj) {
84
+ return obj && obj.__esModule ? obj : {
85
+ default: obj
86
+ };
87
+ }
88
+ function _iterableToArrayLimit(arr, i) {
89
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
90
+ if (_i == null) return;
91
+ var _arr = [];
92
+ var _n = true;
93
+ var _d = false;
94
+ var _s, _e;
95
+ try {
96
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
97
+ _arr.push(_s.value);
98
+ if (i && _arr.length === i) break;
99
+ }
100
+ } catch (err) {
101
+ _d = true;
102
+ _e = err;
103
+ } finally{
104
+ try {
105
+ if (!_n && _i["return"] != null) _i["return"]();
106
+ } finally{
107
+ if (_d) throw _e;
108
+ }
109
+ }
110
+ return _arr;
111
+ }
112
+ function _nonIterableRest() {
113
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
114
+ }
115
+ function _slicedToArray(arr, i) {
116
+ return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
117
+ }
118
+ function _unsupportedIterableToArray(o, minLen) {
119
+ if (!o) return;
120
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
121
+ var n = Object.prototype.toString.call(o).slice(8, -1);
122
+ if (n === "Object" && o.constructor) n = o.constructor.name;
123
+ if (n === "Map" || n === "Set") return Array.from(n);
124
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
125
+ }
126
+ var __generator = (void 0) && (void 0).__generator || function(thisArg, body) {
127
+ var f, y, t, g, _ = {
128
+ label: 0,
129
+ sent: function() {
130
+ if (t[0] & 1) throw t[1];
131
+ return t[1];
132
+ },
133
+ trys: [],
134
+ ops: []
135
+ };
136
+ return g = {
137
+ next: verb(0),
138
+ "throw": verb(1),
139
+ "return": verb(2)
140
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
141
+ return this;
142
+ }), g;
143
+ function verb(n) {
144
+ return function(v) {
145
+ return step([
146
+ n,
147
+ v
148
+ ]);
149
+ };
150
+ }
151
+ function step(op) {
152
+ if (f) throw new TypeError("Generator is already executing.");
153
+ while(_)try {
154
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
155
+ if (y = 0, t) op = [
156
+ op[0] & 2,
157
+ t.value
158
+ ];
159
+ switch(op[0]){
160
+ case 0:
161
+ case 1:
162
+ t = op;
163
+ break;
164
+ case 4:
165
+ _.label++;
166
+ return {
167
+ value: op[1],
168
+ done: false
169
+ };
170
+ case 5:
171
+ _.label++;
172
+ y = op[1];
173
+ op = [
174
+ 0
175
+ ];
176
+ continue;
177
+ case 7:
178
+ op = _.ops.pop();
179
+ _.trys.pop();
180
+ continue;
181
+ default:
182
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
183
+ _ = 0;
184
+ continue;
185
+ }
186
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
187
+ _.label = op[1];
188
+ break;
189
+ }
190
+ if (op[0] === 6 && _.label < t[1]) {
191
+ _.label = t[1];
192
+ t = op;
193
+ break;
194
+ }
195
+ if (t && _.label < t[2]) {
196
+ _.label = t[2];
197
+ _.ops.push(op);
198
+ break;
199
+ }
200
+ if (t[2]) _.ops.pop();
201
+ _.trys.pop();
202
+ continue;
203
+ }
204
+ op = body.call(thisArg, _);
205
+ } catch (e) {
206
+ op = [
207
+ 6,
208
+ e
209
+ ];
210
+ y = 0;
211
+ } finally{
212
+ f = t = 0;
213
+ }
214
+ if (op[0] & 5) throw op[1];
215
+ return {
216
+ value: op[0] ? op[1] : void 0,
217
+ done: true
218
+ };
219
+ }
220
+ };
221
+ var cacheStore = new WeakMap();
222
+ function pMemoize(fn) {
223
+ var ref = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, _cacheKey = ref.cacheKey, cacheKey = _cacheKey === void 0 ? function(param) {
224
+ var _param = _slicedToArray(param, 1), firstArgument = _param[0];
225
+ return firstArgument;
226
+ } : _cacheKey, _cache = ref.cache, cache = _cache === void 0 ? new Map() : _cache;
227
+ // Promise objects can't be serialized so we keep track of them internally and only provide their resolved values to `cache`
228
+ // `Promise<AsyncReturnType<FunctionToMemoize>>` is used instead of `ReturnType<FunctionToMemoize>` because promise properties are not kept
229
+ var promiseCache = new Map();
230
+ var memoized = function memoized() {
231
+ for(var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++){
232
+ arguments_[_key] = arguments[_key];
233
+ }
234
+ var key = cacheKey(arguments_);
235
+ if (promiseCache.has(key)) {
236
+ return promiseCache.get(key);
237
+ }
238
+ var _this = this;
239
+ var promise = _asyncToGenerator(function() {
240
+ var _tmp, promise, result;
241
+ return __generator(this, function(_state) {
242
+ switch(_state.label){
243
+ case 0:
244
+ _state.trys.push([
245
+ 0,
246
+ ,
247
+ 11,
248
+ 12
249
+ ]);
250
+ _tmp = cache;
251
+ if (!_tmp) return [
252
+ 3,
253
+ 2
254
+ ];
255
+ return [
256
+ 4,
257
+ cache.has(key)
258
+ ];
259
+ case 1:
260
+ _tmp = _state.sent();
261
+ _state.label = 2;
262
+ case 2:
263
+ if (!_tmp) return [
264
+ 3,
265
+ 4
266
+ ];
267
+ return [
268
+ 4,
269
+ cache.get(key)
270
+ ];
271
+ case 3:
272
+ return [
273
+ 2,
274
+ _state.sent()
275
+ ];
276
+ case 4:
277
+ promise = fn.apply(_this, arguments_);
278
+ return [
279
+ 4,
280
+ promise
281
+ ];
282
+ case 5:
283
+ result = _state.sent();
284
+ _state.label = 6;
285
+ case 6:
286
+ _state.trys.push([
287
+ 6,
288
+ ,
289
+ 7,
290
+ 10
291
+ ]);
292
+ return [
293
+ 2,
294
+ result
295
+ ];
296
+ case 7:
297
+ if (!cache) return [
298
+ 3,
299
+ 9
300
+ ];
301
+ return [
302
+ 4,
303
+ cache.set(key, result)
304
+ ];
305
+ case 8:
306
+ _state.sent();
307
+ _state.label = 9;
308
+ case 9:
309
+ return [
310
+ 7
311
+ ];
312
+ case 10:
313
+ return [
314
+ 3,
315
+ 12
316
+ ];
317
+ case 11:
318
+ promiseCache.delete(key);
319
+ return [
320
+ 7
321
+ ];
322
+ case 12:
323
+ return [
324
+ 2
325
+ ];
326
+ }
327
+ });
328
+ })();
329
+ promiseCache.set(key, promise);
330
+ return promise;
331
+ };
332
+ (0, _mimicFn.default)(memoized, fn, {
333
+ ignoreNonConfigurable: true
334
+ });
335
+ cacheStore.set(memoized, cache);
336
+ return memoized;
337
+ }
338
+ function pMemoizeDecorator() {
339
+ var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
340
+ var instanceMap = new WeakMap();
341
+ return function(target, propertyKey, descriptor) {
342
+ var input = target[propertyKey]; // eslint-disable-line @typescript-eslint/no-unsafe-assignment
343
+ if (typeof input !== "function") {
344
+ throw new TypeError("The decorated value must be a function");
345
+ }
346
+ delete descriptor.value;
347
+ delete descriptor.writable;
348
+ descriptor.get = function() {
349
+ if (!instanceMap.has(this)) {
350
+ var value = pMemoize(input, options);
351
+ instanceMap.set(this, value);
352
+ return value;
353
+ }
354
+ return instanceMap.get(this);
355
+ };
356
+ };
357
+ }
358
+ function pMemoizeClear(fn) {
359
+ if (!cacheStore.has(fn)) {
360
+ throw new TypeError("Can't clear a function that was not memoized!");
361
+ }
362
+ var cache = cacheStore.get(fn);
363
+ if (!cache) {
364
+ throw new TypeError("Can't clear a function that doesn't use a cache!");
365
+ }
366
+ if (typeof cache.clear !== "function") {
367
+ throw new TypeError("The cache Map can't be cleared!");
368
+ }
369
+ cache.clear();
370
+ }
package/license ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@common.js/p-memoize",
3
+ "version": "7.1.0",
4
+ "description": "Memoize promise-returning & async functions",
5
+ "license": "MIT",
6
+ "repository": "etienne-martin/common.js",
7
+ "funding": "https://github.com/sindresorhus/p-memoize?sponsor=1",
8
+ "type": "commonjs",
9
+ "types": "dist/index.d.ts",
10
+ "engines": {
11
+ "node": ">=14.16"
12
+ },
13
+ "scripts": {
14
+ "test": "xo && ava && npm run build && tsd",
15
+ "build": "del-cli dist && tsc"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "dependencies": {
21
+ "@common.js/mimic-fn": "^4.0.0"
22
+ },
23
+ "devDependencies": {
24
+ "@sindresorhus/tsconfig": "^3.0.1",
25
+ "@types/serialize-javascript": "^5.0.2",
26
+ "ava": "^4.3.0",
27
+ "del-cli": "^4.0.1",
28
+ "delay": "^5.0.0",
29
+ "p-defer": "^4.0.0",
30
+ "p-state": "^1.0.0",
31
+ "serialize-javascript": "^6.0.0",
32
+ "ts-node": "^10.8.2",
33
+ "tsd": "^0.22.0",
34
+ "xo": "^0.50.0"
35
+ },
36
+ "ava": {
37
+ "extensions": {
38
+ "ts": "module"
39
+ },
40
+ "nodeArguments": [
41
+ "--loader=ts-node/esm"
42
+ ]
43
+ },
44
+ "xo": {
45
+ "rules": {
46
+ "@typescript-eslint/no-redundant-type-constituents": "off"
47
+ }
48
+ },
49
+ "homepage": "https://github.com/etienne-martin/common.js#readme",
50
+ "main": "./dist/index.js"
51
+ }
package/readme.md ADDED
@@ -0,0 +1,154 @@
1
+ # p-memoize
2
+
3
+ > [Memoize](https://en.wikipedia.org/wiki/Memoization) promise-returning & async functions
4
+
5
+ Useful for speeding up consecutive function calls by caching the result of calls with identical input.
6
+
7
+ <!-- Please keep this section in sync with https://github.com/sindresorhus/mem/blob/main/readme.md -->
8
+
9
+ By default, **only the memoized function's first argument is considered** via strict equality comparison. If you need to cache multiple arguments or cache `object`s *by value*, have a look at alternative [caching strategies](#caching-strategy) below.
10
+
11
+ This package is similar to [mem](https://github.com/sindresorhus/mem) but with async-specific enhancements; in particular, it allows for asynchronous caches and does not cache rejected promises.
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ npm install p-memoize
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ```js
22
+ import pMemoize from 'p-memoize';
23
+ import got from 'got';
24
+
25
+ const memoizedGot = pMemoize(got);
26
+
27
+ await memoizedGot('https://sindresorhus.com');
28
+
29
+ // This call is cached
30
+ await memoizedGot('https://sindresorhus.com');
31
+ ```
32
+
33
+ ### Caching strategy
34
+
35
+ Similar to the [caching strategy for `mem`](https://github.com/sindresorhus/mem#options) with the following exceptions:
36
+
37
+ - Promises returned from a memoized function are locally cached until resolving, when their value is added to `cache`. Special properties assigned to a returned promise will not be kept after resolution and every promise may need to resolve with a serializable object if caching results in a database.
38
+ - `.get()`, `.has()` and `.set()` methods on `cache` can run asynchronously by returning a promise.
39
+ - Instead of `.set()` being provided an object with the properties `value` and `maxAge`, it will only be provided `value` as the first argument. If you want to implement time-based expiry, consider [doing so in `cache`](#time-based-cache-expiration).
40
+
41
+ ## API
42
+
43
+ ### pMemoize(fn, options?)
44
+
45
+ Returns a memoized version of the given function.
46
+
47
+ #### fn
48
+
49
+ Type: `Function`
50
+
51
+ Promise-returning or async function to be memoized.
52
+
53
+ #### options
54
+
55
+ Type: `object`
56
+
57
+ See the [`mem` options](https://github.com/sindresorhus/mem#options) in addition to the below option.
58
+
59
+ ##### cacheKey
60
+
61
+ Type: `Function`\
62
+ Default: `arguments_ => arguments_[0]`\
63
+ Example: `arguments_ => JSON.stringify(arguments_)`
64
+
65
+ Determines the cache key for storing the result based on the function arguments. By default, **only the first argument is considered**.
66
+
67
+ A `cacheKey` function can return any type supported by `Map` (or whatever structure you use in the `cache` option).
68
+
69
+ See the [caching strategy](#caching-strategy) section for more information.
70
+
71
+ ##### cache
72
+
73
+ Type: `object | false`\
74
+ Default: `new Map()`
75
+
76
+ Use a different cache storage. Must implement the following methods: `.has(key)`, `.get(key)`, `.set(key, value)`, `.delete(key)`, and optionally `.clear()`. You could for example use a `WeakMap` instead or [`quick-lru`](https://github.com/sindresorhus/quick-lru) for a LRU cache. To disable caching so that only concurrent executions resolve with the same value, pass `false`.
77
+
78
+ See the [caching strategy](https://github.com/sindresorhus/mem#caching-strategy) section in the `mem` package for more information.
79
+
80
+ ### pMemoizeDecorator(options)
81
+
82
+ Returns a [decorator](https://github.com/tc39/proposal-decorators) to memoize class methods or static class methods.
83
+
84
+ Notes:
85
+
86
+ - Only class methods and getters/setters can be memoized, not regular functions (they aren't part of the proposal);
87
+ - Only [TypeScript’s decorators](https://www.typescriptlang.org/docs/handbook/decorators.html#parameter-decorators) are supported, not [Babel’s](https://babeljs.io/docs/en/babel-plugin-proposal-decorators), which use a different version of the proposal;
88
+ - Being an experimental feature, they need to be enabled with `--experimentalDecorators`; follow TypeScript’s docs.
89
+
90
+ #### options
91
+
92
+ Type: `object`
93
+
94
+ Same as options for `pMemoize()`.
95
+
96
+ ```ts
97
+ import {pMemoizeDecorator} from 'p-memoize';
98
+
99
+ class Example {
100
+ index = 0
101
+
102
+ @pMemoizeDecorator()
103
+ async counter() {
104
+ return ++this.index;
105
+ }
106
+ }
107
+
108
+ class ExampleWithOptions {
109
+ index = 0
110
+
111
+ @pMemoizeDecorator()
112
+ async counter() {
113
+ return ++this.index;
114
+ }
115
+ }
116
+ ```
117
+
118
+ ### pMemoizeClear(memoized)
119
+
120
+ Clear all cached data of a memoized function.
121
+
122
+ It will throw when given a non-memoized function.
123
+
124
+ ## Tips
125
+
126
+ ### Time-based cache expiration
127
+
128
+ ```js
129
+ import pMemoize from 'p-memoize';
130
+ import ExpiryMap from 'expiry-map';
131
+ import got from 'got';
132
+
133
+ const cache = new ExpiryMap(10000); // Cached values expire after 10 seconds
134
+
135
+ const memoizedGot = pMemoize(got, {cache});
136
+ ```
137
+
138
+ ### Caching promise rejections
139
+
140
+ ```js
141
+ import pMemoize from 'p-memoize';
142
+ import pReflect from 'p-reflect';
143
+
144
+ const memoizedGot = pMemoize(async (url, options) => pReflect(got(url, options)));
145
+
146
+ await memoizedGot('https://example.com');
147
+ // {isFulfilled: true, isRejected: false, value: '...'}
148
+ ```
149
+
150
+ ## Related
151
+
152
+ - [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions
153
+ - [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions
154
+ - [More…](https://github.com/sindresorhus/promise-fun)