UNPKG

4.37 kBTypeScriptView Raw
1import type { AsyncReturnType } from 'type-fest';
2export declare type AnyAsyncFunction = (...arguments_: readonly any[]) => Promise<unknown | void>;
3export declare type 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};
10export declare type 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```
52import {setTimeout as delay} from 'node:timer/promises';
53import pMemoize from 'p-memoize';
54import got from 'got';
55
56const memoizedGot = pMemoize(got);
57
58await memoizedGot('https://sindresorhus.com');
59
60// This call is cached
61await memoizedGot('https://sindresorhus.com');
62
63await delay(2000);
64
65// This call is not cached as the cache has expired
66await memoizedGot('https://sindresorhus.com');
67```
68*/
69export 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```
79import {pMemoizeDecorator} from 'p-memoize';
80
81class Example {
82 index = 0
83
84 @pMemoizeDecorator()
85 async counter() {
86 return ++this.index;
87 }
88}
89
90class ExampleWithOptions {
91 index = 0
92
93 @pMemoizeDecorator()
94 async counter() {
95 return ++this.index;
96 }
97}
98```
99*/
100export declare function pMemoizeDecorator<FunctionToMemoize extends AnyAsyncFunction, CacheKeyType>(options?: Options<FunctionToMemoize, CacheKeyType>): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => void;
101/**
102Clear all cached data of a memoized function.
103
104@param fn - Memoized function.
105*/
106export declare function pMemoizeClear(fn: AnyAsyncFunction): void;