@chriscdn/memoize 1.0.6 → 1.0.8
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 +16 -14
- package/__tests__/memoize.test.ts +94 -0
- package/lib/index.d.ts +4 -15
- package/lib/memoize.cjs +1 -1
- package/lib/memoize.cjs.map +1 -1
- package/lib/memoize.modern.js +1 -1
- package/lib/memoize.modern.js.map +1 -1
- package/lib/memoize.module.js +1 -1
- package/lib/memoize.module.js.map +1 -1
- package/package.json +2 -3
- package/src/index.ts +9 -53
package/README.md
CHANGED
|
@@ -18,18 +18,15 @@ yarn add @chriscdn/memoize
|
|
|
18
18
|
|
|
19
19
|
## Usage
|
|
20
20
|
|
|
21
|
-
The package provides two functions: `Memoize` and `MemoizeAsync`.
|
|
22
|
-
|
|
23
21
|
```ts
|
|
24
|
-
import { Memoize
|
|
22
|
+
import { Memoize } from "@chriscdn/memoize";
|
|
25
23
|
```
|
|
26
24
|
|
|
27
|
-
|
|
28
|
-
- **`MemoizeAsync`** is used to memoize an _asynchronous_ function.
|
|
25
|
+
The **`Memoize`** function can be used to memoize a _synchronous_ or _asynchronous_ function.
|
|
29
26
|
|
|
30
|
-
The cache is powered by [quick-lru](https://www.npmjs.com/package/quick-lru). Each call to `Memoize`
|
|
27
|
+
The cache is powered by [quick-lru](https://www.npmjs.com/package/quick-lru). Each call to `Memoize` creates a new cache instance.
|
|
31
28
|
|
|
32
|
-
The `
|
|
29
|
+
The `Memoize` function prevents duplicate evaluations by ensuring that multiple calls with the same cache key are processed only once. This includes asynchronous functions.
|
|
33
30
|
|
|
34
31
|
By default, the cache key is generated by calling `JSON.stringify()` on the function arguments. This behavior can be customized (see below).
|
|
35
32
|
|
|
@@ -63,7 +60,7 @@ Memoizing an asynchronous function is similar:
|
|
|
63
60
|
```ts
|
|
64
61
|
const _add = async (x: number, y: number) => x + y;
|
|
65
62
|
|
|
66
|
-
const add =
|
|
63
|
+
const add = Memoize(_add);
|
|
67
64
|
|
|
68
65
|
const result = await add(5, 7);
|
|
69
66
|
// 12
|
|
@@ -71,23 +68,26 @@ const result = await add(5, 7);
|
|
|
71
68
|
|
|
72
69
|
## Options
|
|
73
70
|
|
|
74
|
-
|
|
71
|
+
The `Memoize` function accepts an `options` parameter to control the cache behavior:
|
|
75
72
|
|
|
76
73
|
```ts
|
|
77
|
-
const add =
|
|
74
|
+
const add = Memoize(_add, options);
|
|
78
75
|
```
|
|
79
76
|
|
|
80
77
|
Available options (with defaults):
|
|
81
78
|
|
|
82
79
|
```ts
|
|
83
80
|
const options = {
|
|
84
|
-
//
|
|
81
|
+
// The maximum number of items in the cache.
|
|
85
82
|
maxSize: 1000,
|
|
86
83
|
|
|
87
|
-
//
|
|
84
|
+
// The maximum duration (in milliseconds) an item can remain in the cache. If set to `undefined`, the item will not expire due to time constraints.
|
|
88
85
|
maxAge: undefined,
|
|
89
86
|
|
|
90
|
-
// A synchronous function to
|
|
87
|
+
// A synchronous function that returns `true` or `false` to determine whether to add the returnValue to the cache.
|
|
88
|
+
shouldCache: (returnValue: Return, key: string) => true,
|
|
89
|
+
|
|
90
|
+
// A synchronous function to generate a cache key (must return a string).
|
|
91
91
|
resolver: (...args) => JSON.stringify(args),
|
|
92
92
|
};
|
|
93
93
|
```
|
|
@@ -97,7 +97,7 @@ const options = {
|
|
|
97
97
|
The underlying [quick-lru](https://www.npmjs.com/package/quick-lru) instance is accessible via the `.cache` property on the memoized function:
|
|
98
98
|
|
|
99
99
|
```ts
|
|
100
|
-
const add =
|
|
100
|
+
const add = Memoize(_add);
|
|
101
101
|
const result = await add(5, 7);
|
|
102
102
|
|
|
103
103
|
console.log(add.cache.size === 1);
|
|
@@ -107,6 +107,8 @@ console.log(add.cache.size === 1);
|
|
|
107
107
|
add.cache.clear();
|
|
108
108
|
```
|
|
109
109
|
|
|
110
|
+
The values `null` and `undefined` are cached by default, but this behavior can be adjusted using the `shouldCache` option.
|
|
111
|
+
|
|
110
112
|
## Class Methods
|
|
111
113
|
|
|
112
114
|
Class methods can also be memoized, but this requires overriding the method within the constructor. Ensure you bind the method to the instance to maintain the correct context.
|
|
@@ -102,3 +102,97 @@ describe("Memoization of Class methods", () => {
|
|
|
102
102
|
expect(obj.count).toBe(2);
|
|
103
103
|
});
|
|
104
104
|
});
|
|
105
|
+
|
|
106
|
+
describe("Null & Undefined Cases", () => {
|
|
107
|
+
const UndefinedFunc = Memoize((key: string) => undefined, {
|
|
108
|
+
resolver: (key) => key,
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
const NullFunc = Memoize((key: string) => undefined, {
|
|
112
|
+
resolver: (key) => key,
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it("Undefined", () => {
|
|
116
|
+
expect(UndefinedFunc.cache.has("hello")).toBe(false);
|
|
117
|
+
expect(UndefinedFunc("hello")).toBe(undefined);
|
|
118
|
+
expect(UndefinedFunc.cache.has("hello")).toBe(true);
|
|
119
|
+
expect(UndefinedFunc("hello")).toBe(undefined);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it("Null", () => {
|
|
123
|
+
expect(NullFunc.cache.has("hello")).toBe(false);
|
|
124
|
+
expect(NullFunc("hello")).toBe(undefined);
|
|
125
|
+
expect(NullFunc.cache.has("hello")).toBe(true);
|
|
126
|
+
expect(NullFunc("hello")).toBe(undefined);
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
describe("Object Reference", () => {
|
|
131
|
+
const a = { hello: "world" };
|
|
132
|
+
|
|
133
|
+
const funny = Memoize(() => a);
|
|
134
|
+
|
|
135
|
+
it("Null", () => {
|
|
136
|
+
expect(funny().hello).toBe("world");
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it("Null", () => {
|
|
140
|
+
a.hello = "mars";
|
|
141
|
+
expect(funny().hello).toBe("mars");
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
describe("ShouldCache", () => {
|
|
146
|
+
const doNotCache = "do not cache";
|
|
147
|
+
|
|
148
|
+
const myFunction = Memoize((word: string) => word, {
|
|
149
|
+
shouldCache: (value) => value !== doNotCache,
|
|
150
|
+
resolver: (value) => value,
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
myFunction("hi");
|
|
154
|
+
myFunction(doNotCache);
|
|
155
|
+
|
|
156
|
+
it("should be cached", () => {
|
|
157
|
+
expect(myFunction.cache.has("hi")).toBe(true);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
it("should not be cached", () => {
|
|
161
|
+
expect(myFunction.cache.has(doNotCache)).toBe(false);
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
describe("Do we need MemoizeAsync?", async () => {
|
|
166
|
+
const myFunction = Memoize(async (word: string) => word, {
|
|
167
|
+
resolver: (value) => value,
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
it("should be cached", async () => {
|
|
171
|
+
expect(await myFunction("hi")).toBe("hi");
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
it("should be cached", async () => {
|
|
175
|
+
expect(await myFunction("hi")).toBe("hi");
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it("should be cached", async () => {
|
|
179
|
+
expect(await myFunction("hi2")).toBe("hi2");
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
it("size", () => expect(myFunction.cache.size).toBe(2));
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
describe("Errors", async () => {
|
|
186
|
+
const errorSync = Memoize(() => {
|
|
187
|
+
throw new Error("errorsync");
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
const errorASync = Memoize(async () => {
|
|
191
|
+
throw new Error("errorasync");
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it("error sync", () => expect(() => errorSync()).toThrowError("errorsync"));
|
|
195
|
+
|
|
196
|
+
it("error async", () =>
|
|
197
|
+
expect(errorASync()).rejects.toThrowError("errorasync"));
|
|
198
|
+
});
|
package/lib/index.d.ts
CHANGED
|
@@ -1,26 +1,15 @@
|
|
|
1
1
|
import QuickLRU from "quick-lru";
|
|
2
|
-
type Options<T extends any[]> = {
|
|
2
|
+
type Options<T extends any[], Return> = {
|
|
3
3
|
maxSize: number;
|
|
4
4
|
maxAge?: number;
|
|
5
|
+
shouldCache: (returnValue: Return, key: string) => boolean;
|
|
5
6
|
resolver: (...args: T) => string;
|
|
6
7
|
};
|
|
7
8
|
/**
|
|
8
9
|
* Memoize a synchronous function.
|
|
9
10
|
*/
|
|
10
|
-
declare const Memoize: <Args extends unknown[], Return>(cb: (...args: Args) => Return, options?: Partial<Options<Args>>) => {
|
|
11
|
+
declare const Memoize: <Args extends unknown[], Return>(cb: (...args: Args) => Return, options?: Partial<Options<Args, Return>>) => {
|
|
11
12
|
(...args: Args): Return;
|
|
12
13
|
cache: QuickLRU<string, Return>;
|
|
13
14
|
};
|
|
14
|
-
|
|
15
|
-
* Memoize an asynchronous function.
|
|
16
|
-
*
|
|
17
|
-
* This differs from the synchronous case by ensuring multiple calls with the
|
|
18
|
-
* same arguments is only evaluated once. This is controlled by using a
|
|
19
|
-
* semaphore, which forces redundant calls to wait until the first call
|
|
20
|
-
* completes.
|
|
21
|
-
*/
|
|
22
|
-
declare const MemoizeAsync: <Args extends unknown[], Return>(cb: (...args: Args) => Promise<Return>, options?: Partial<Options<Args>>) => {
|
|
23
|
-
(...args: Args): Promise<Return>;
|
|
24
|
-
cache: QuickLRU<string, Return>;
|
|
25
|
-
};
|
|
26
|
-
export { Memoize, MemoizeAsync };
|
|
15
|
+
export { Memoize, Memoize as MemoizeAsync };
|
package/lib/memoize.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=/*#__PURE__*/e(require("quick-lru")),n=function(e,n){var t,u,i;void 0===n&&(n={});var l=null!=(t=n.maxSize)?t:1e3,a=null!=(u=n.shouldCache)?u:function(){return!0},o=null!=(i=n.resolver)?i:function(){return JSON.stringify([].slice.call(arguments))},c=new r.default({maxAge:n.maxAge,maxSize:l}),f=function(){var r=[].slice.call(arguments),n=o.apply(void 0,r);if(c.has(n))return c.get(n);var t=e.apply(void 0,r);return a(t,n)&&c.set(n,t),t};return f.cache=c,f};exports.Memoize=n,exports.MemoizeAsync=n;
|
|
2
2
|
//# sourceMappingURL=memoize.cjs.map
|
package/lib/memoize.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memoize.cjs","sources":["../src/index.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"memoize.cjs","sources":["../src/index.ts"],"sourcesContent":["import QuickLRU from \"quick-lru\";\n\nconst kDefaultMaxSize = 1000;\n\ntype Options<T extends any[], Return> = {\n maxSize: number;\n maxAge?: number;\n shouldCache: (returnValue: Return, key: string) => boolean;\n resolver: (...args: T) => string;\n};\n\n/**\n * Memoize a synchronous function.\n */\nconst Memoize = <Args extends unknown[], Return>(\n cb: (...args: Args) => Return,\n options: Partial<Options<Args, Return>> = {},\n) => {\n const maxAge: number | undefined = options.maxAge;\n const maxSize = options.maxSize ?? kDefaultMaxSize;\n const shouldCache = options.shouldCache ?? (() => true);\n\n const resolver =\n options.resolver ?? ((...args: Args) => JSON.stringify(args));\n\n const cache = new QuickLRU<string, Return>({\n maxAge,\n maxSize,\n });\n\n const memoizedFunction = (...args: Args): Return => {\n const key = resolver(...args);\n\n if (cache.has(key)) {\n return cache.get(key);\n } else {\n const returnValue = cb(...args);\n if (shouldCache(returnValue, key)) {\n cache.set(key, returnValue);\n }\n return returnValue;\n }\n };\n\n memoizedFunction.cache = cache;\n\n return memoizedFunction;\n};\n\nexport { Memoize, Memoize as MemoizeAsync };\n"],"names":["Memoize","cb","options","_options$maxSize","_options$shouldCache","_options$resolver","maxSize","shouldCache","resolver","JSON","stringify","slice","call","arguments","cache","QuickLRU","maxAge","memoizedFunction","args","key","apply","has","get","returnValue","set"],"mappings":"mHAcMA,EAAU,SACdC,EACAC,GACE,IAAAC,EAAAC,EAAAC,OADFH,IAAAA,IAAAA,EAA0C,CAAA,GAE1C,IACMI,SAAOH,EAAGD,EAAQI,SAAOH,EAjBT,IAkBhBI,SAAWH,EAAGF,EAAQK,aAAWH,EAAK,WAAM,OAAA,CAAI,EAEhDI,EACY,OADJH,EACZH,EAAQM,UAAQH,EAAK,WAAmB,OAAAI,KAAKC,UAASC,GAAAA,MAAAC,KAAAC,WAAM,EAExDC,EAAQ,IAAIC,EAAQ,QAAiB,CACzCC,OARiCd,EAAQc,OASzCV,QAAAA,IAGIW,EAAmB,WAAI,IAAAC,EAAUP,GAAAA,MAAAC,KAAAC,WAC/BM,EAAMX,EAAQY,WAAIF,EAAAA,GAExB,GAAIJ,EAAMO,IAAIF,GACZ,OAAOL,EAAMQ,IAAIH,GAEjB,IAAMI,EAActB,EAAEmB,WAAIF,EAAAA,GAI1B,OAHIX,EAAYgB,EAAaJ,IAC3BL,EAAMU,IAAIL,EAAKI,GAEVA,CAEX,EAIA,OAFAN,EAAiBH,MAAQA,EAElBG,CACT"}
|
package/lib/memoize.modern.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"
|
|
1
|
+
import e from"quick-lru";const r=(r,n={})=>{var t,s,o;const a=null!=(t=n.maxSize)?t:1e3,c=null!=(s=n.shouldCache)?s:()=>!0,l=null!=(o=n.resolver)?o:(...e)=>JSON.stringify(e),u=new e({maxAge:n.maxAge,maxSize:a}),i=(...e)=>{const n=l(...e);if(u.has(n))return u.get(n);{const t=r(...e);return c(t,n)&&u.set(n,t),t}};return i.cache=u,i};export{r as Memoize,r as MemoizeAsync};
|
|
2
2
|
//# sourceMappingURL=memoize.modern.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memoize.modern.js","sources":["../src/index.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"memoize.modern.js","sources":["../src/index.ts"],"sourcesContent":["import QuickLRU from \"quick-lru\";\n\nconst kDefaultMaxSize = 1000;\n\ntype Options<T extends any[], Return> = {\n maxSize: number;\n maxAge?: number;\n shouldCache: (returnValue: Return, key: string) => boolean;\n resolver: (...args: T) => string;\n};\n\n/**\n * Memoize a synchronous function.\n */\nconst Memoize = <Args extends unknown[], Return>(\n cb: (...args: Args) => Return,\n options: Partial<Options<Args, Return>> = {},\n) => {\n const maxAge: number | undefined = options.maxAge;\n const maxSize = options.maxSize ?? kDefaultMaxSize;\n const shouldCache = options.shouldCache ?? (() => true);\n\n const resolver =\n options.resolver ?? ((...args: Args) => JSON.stringify(args));\n\n const cache = new QuickLRU<string, Return>({\n maxAge,\n maxSize,\n });\n\n const memoizedFunction = (...args: Args): Return => {\n const key = resolver(...args);\n\n if (cache.has(key)) {\n return cache.get(key);\n } else {\n const returnValue = cb(...args);\n if (shouldCache(returnValue, key)) {\n cache.set(key, returnValue);\n }\n return returnValue;\n }\n };\n\n memoizedFunction.cache = cache;\n\n return memoizedFunction;\n};\n\nexport { Memoize, Memoize as MemoizeAsync };\n"],"names":["Memoize","cb","options","_options$maxSize","_options$shouldCache","_options$resolver","maxSize","shouldCache","resolver","args","JSON","stringify","cache","QuickLRU","maxAge","memoizedFunction","key","has","get","returnValue","set"],"mappings":"yBAEA,MAYMA,EAAUA,CACdC,EACAC,EAA0C,CAAE,KAC1CC,IAAAA,EAAAC,EAAAC,EACF,MACMC,SAAOH,EAAGD,EAAQI,SAAOH,EAjBT,IAkBhBI,EAAiC,OAAtBH,EAAGF,EAAQK,aAAWH,EAAK,KAAM,EAE5CI,EACYH,OADJA,EACZH,EAAQM,UAAQH,EAAK,IAAII,IAAeC,KAAKC,UAAUF,GAEnDG,EAAQ,IAAIC,EAAyB,CACzCC,OARiCZ,EAAQY,OASzCR,YAGIS,EAAmBA,IAAIN,KAC3B,MAAMO,EAAMR,KAAYC,GAExB,GAAIG,EAAMK,IAAID,GACZ,OAAOJ,EAAMM,IAAIF,GACZ,CACL,MAAMG,EAAclB,KAAMQ,GAI1B,OAHIF,EAAYY,EAAaH,IAC3BJ,EAAMQ,IAAIJ,EAAKG,GAEVA,CACR,GAKH,OAFAJ,EAAiBH,MAAQA,EAElBG"}
|
package/lib/memoize.module.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"
|
|
1
|
+
import e from"quick-lru";var r=function(r,n){var a,i,l;void 0===n&&(n={});var u=null!=(a=n.maxSize)?a:1e3,t=null!=(i=n.shouldCache)?i:function(){return!0},c=null!=(l=n.resolver)?l:function(){return JSON.stringify([].slice.call(arguments))},o=new e({maxAge:n.maxAge,maxSize:u}),s=function(){var e=[].slice.call(arguments),n=c.apply(void 0,e);if(o.has(n))return o.get(n);var a=r.apply(void 0,e);return t(a,n)&&o.set(n,a),a};return s.cache=o,s};export{r as Memoize,r as MemoizeAsync};
|
|
2
2
|
//# sourceMappingURL=memoize.module.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memoize.module.js","sources":["../src/index.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"memoize.module.js","sources":["../src/index.ts"],"sourcesContent":["import QuickLRU from \"quick-lru\";\n\nconst kDefaultMaxSize = 1000;\n\ntype Options<T extends any[], Return> = {\n maxSize: number;\n maxAge?: number;\n shouldCache: (returnValue: Return, key: string) => boolean;\n resolver: (...args: T) => string;\n};\n\n/**\n * Memoize a synchronous function.\n */\nconst Memoize = <Args extends unknown[], Return>(\n cb: (...args: Args) => Return,\n options: Partial<Options<Args, Return>> = {},\n) => {\n const maxAge: number | undefined = options.maxAge;\n const maxSize = options.maxSize ?? kDefaultMaxSize;\n const shouldCache = options.shouldCache ?? (() => true);\n\n const resolver =\n options.resolver ?? ((...args: Args) => JSON.stringify(args));\n\n const cache = new QuickLRU<string, Return>({\n maxAge,\n maxSize,\n });\n\n const memoizedFunction = (...args: Args): Return => {\n const key = resolver(...args);\n\n if (cache.has(key)) {\n return cache.get(key);\n } else {\n const returnValue = cb(...args);\n if (shouldCache(returnValue, key)) {\n cache.set(key, returnValue);\n }\n return returnValue;\n }\n };\n\n memoizedFunction.cache = cache;\n\n return memoizedFunction;\n};\n\nexport { Memoize, Memoize as MemoizeAsync };\n"],"names":["Memoize","cb","options","_options$maxSize","_options$shouldCache","_options$resolver","maxSize","shouldCache","resolver","JSON","stringify","slice","call","arguments","cache","QuickLRU","maxAge","memoizedFunction","args","key","apply","has","get","returnValue","set"],"mappings":"yBAEA,IAYMA,EAAU,SACdC,EACAC,GACE,IAAAC,EAAAC,EAAAC,OADFH,IAAAA,IAAAA,EAA0C,CAAA,GAE1C,IACMI,SAAOH,EAAGD,EAAQI,SAAOH,EAjBT,IAkBhBI,SAAWH,EAAGF,EAAQK,aAAWH,EAAK,WAAM,OAAA,CAAI,EAEhDI,EACY,OADJH,EACZH,EAAQM,UAAQH,EAAK,WAAmB,OAAAI,KAAKC,UAASC,GAAAA,MAAAC,KAAAC,WAAM,EAExDC,EAAQ,IAAIC,EAAyB,CACzCC,OARiCd,EAAQc,OASzCV,QAAAA,IAGIW,EAAmB,WAAI,IAAAC,EAAUP,GAAAA,MAAAC,KAAAC,WAC/BM,EAAMX,EAAQY,WAAIF,EAAAA,GAExB,GAAIJ,EAAMO,IAAIF,GACZ,OAAOL,EAAMQ,IAAIH,GAEjB,IAAMI,EAActB,EAAEmB,WAAIF,EAAAA,GAI1B,OAHIX,EAAYgB,EAAaJ,IAC3BL,EAAMU,IAAIL,EAAKI,GAEVA,CAEX,EAIA,OAFAN,EAAiBH,MAAQA,EAElBG,CACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chriscdn/memoize",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.8",
|
|
4
4
|
"description": "Memoize a synchronous or asynchronous function.",
|
|
5
5
|
"repository": "https://github.com/chriscdn/memoize",
|
|
6
6
|
"author": "Christopher Meyer <chris@schwiiz.org>",
|
|
@@ -22,11 +22,10 @@
|
|
|
22
22
|
"test": "vitest"
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@chriscdn/promise-semaphore": "^2.0.10",
|
|
26
25
|
"quick-lru": "^7.0.0"
|
|
27
26
|
},
|
|
28
27
|
"devDependencies": {
|
|
29
28
|
"microbundle": "^0.15.1",
|
|
30
|
-
"vitest": "^3.0.
|
|
29
|
+
"vitest": "^3.0.9"
|
|
31
30
|
}
|
|
32
31
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import Semaphore from "@chriscdn/promise-semaphore";
|
|
2
1
|
import QuickLRU from "quick-lru";
|
|
3
2
|
|
|
4
3
|
const kDefaultMaxSize = 1000;
|
|
5
4
|
|
|
6
|
-
type Options<T extends any[]> = {
|
|
5
|
+
type Options<T extends any[], Return> = {
|
|
7
6
|
maxSize: number;
|
|
8
7
|
maxAge?: number;
|
|
8
|
+
shouldCache: (returnValue: Return, key: string) => boolean;
|
|
9
9
|
resolver: (...args: T) => string;
|
|
10
10
|
};
|
|
11
11
|
|
|
@@ -14,10 +14,11 @@ type Options<T extends any[]> = {
|
|
|
14
14
|
*/
|
|
15
15
|
const Memoize = <Args extends unknown[], Return>(
|
|
16
16
|
cb: (...args: Args) => Return,
|
|
17
|
-
options: Partial<Options<Args>> = {},
|
|
17
|
+
options: Partial<Options<Args, Return>> = {},
|
|
18
18
|
) => {
|
|
19
19
|
const maxAge: number | undefined = options.maxAge;
|
|
20
20
|
const maxSize = options.maxSize ?? kDefaultMaxSize;
|
|
21
|
+
const shouldCache = options.shouldCache ?? (() => true);
|
|
21
22
|
|
|
22
23
|
const resolver =
|
|
23
24
|
options.resolver ?? ((...args: Args) => JSON.stringify(args));
|
|
@@ -34,7 +35,9 @@ const Memoize = <Args extends unknown[], Return>(
|
|
|
34
35
|
return cache.get(key);
|
|
35
36
|
} else {
|
|
36
37
|
const returnValue = cb(...args);
|
|
37
|
-
|
|
38
|
+
if (shouldCache(returnValue, key)) {
|
|
39
|
+
cache.set(key, returnValue);
|
|
40
|
+
}
|
|
38
41
|
return returnValue;
|
|
39
42
|
}
|
|
40
43
|
};
|
|
@@ -45,55 +48,8 @@ const Memoize = <Args extends unknown[], Return>(
|
|
|
45
48
|
};
|
|
46
49
|
|
|
47
50
|
/**
|
|
48
|
-
* Memoize
|
|
49
|
-
*
|
|
50
|
-
* This differs from the synchronous case by ensuring multiple calls with the
|
|
51
|
-
* same arguments is only evaluated once. This is controlled by using a
|
|
52
|
-
* semaphore, which forces redundant calls to wait until the first call
|
|
53
|
-
* completes.
|
|
51
|
+
* @deprecated `Memoize` can be used for asynchronous functions.
|
|
54
52
|
*/
|
|
55
|
-
const MemoizeAsync =
|
|
56
|
-
cb: (...args: Args) => Promise<Return>,
|
|
57
|
-
options: Partial<Options<Args>> = {},
|
|
58
|
-
) => {
|
|
59
|
-
const maxAge: number | undefined = options.maxAge;
|
|
60
|
-
const maxSize = options.maxSize ?? kDefaultMaxSize;
|
|
61
|
-
|
|
62
|
-
const resolver =
|
|
63
|
-
options.resolver ?? ((...args: Args) => JSON.stringify(args));
|
|
64
|
-
|
|
65
|
-
const semaphore = new Semaphore();
|
|
66
|
-
|
|
67
|
-
const cache = new QuickLRU<string, Return>({
|
|
68
|
-
maxAge,
|
|
69
|
-
maxSize,
|
|
70
|
-
});
|
|
71
|
-
|
|
72
|
-
const memoizedFunction = async (...args: Args): Promise<Return> => {
|
|
73
|
-
const key = resolver(...args);
|
|
74
|
-
|
|
75
|
-
if (cache.has(key)) {
|
|
76
|
-
return cache.get(key)!;
|
|
77
|
-
} else {
|
|
78
|
-
try {
|
|
79
|
-
await semaphore.acquire(key);
|
|
80
|
-
|
|
81
|
-
if (cache.has(key)) {
|
|
82
|
-
return cache.get(key);
|
|
83
|
-
} else {
|
|
84
|
-
const returnValue = await cb(...args);
|
|
85
|
-
cache.set(key, returnValue);
|
|
86
|
-
return returnValue;
|
|
87
|
-
}
|
|
88
|
-
} finally {
|
|
89
|
-
semaphore.release(key);
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
};
|
|
93
|
-
|
|
94
|
-
memoizedFunction.cache = cache;
|
|
95
|
-
|
|
96
|
-
return memoizedFunction;
|
|
97
|
-
};
|
|
53
|
+
const MemoizeAsync = Memoize;
|
|
98
54
|
|
|
99
55
|
export { Memoize, MemoizeAsync };
|