@chriscdn/memoize 1.0.3 → 1.0.5
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 +23 -0
- package/__tests__/memoize.test.ts +77 -30
- package/lib/index.d.ts +1 -1
- package/lib/memoize.cjs.map +1 -1
- package/lib/memoize.modern.js.map +1 -1
- package/lib/memoize.module.js.map +1 -1
- package/package.json +3 -3
- package/src/index.ts +56 -56
package/README.md
CHANGED
|
@@ -97,6 +97,29 @@ console.log(addCachedAsync.cache.size === 1);
|
|
|
97
97
|
// true
|
|
98
98
|
```
|
|
99
99
|
|
|
100
|
+
## Class Methods
|
|
101
|
+
|
|
102
|
+
Class methods can also be memoized, though this requires overriding the method within the constructor. When doing so, it's important to bind the method to the instance to ensure it maintains the correct context.
|
|
103
|
+
|
|
104
|
+
Consider the following example, where the `add` method is memoized by reassigning it within the constructor after binding it to the current instance. This ensures the memoized version retains access to instance properties like `count` and keeps TypeScript happy by preserving the method's type signature.
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
class AddClass {
|
|
108
|
+
count: number = 0;
|
|
109
|
+
|
|
110
|
+
constructor() {
|
|
111
|
+
this.add = Memoize(this.add.bind(this));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
add(x: number, y: number) {
|
|
115
|
+
this.count += 1;
|
|
116
|
+
return x + y;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Keep in mind that each instance of a class will maintain its own separate cache.
|
|
122
|
+
|
|
100
123
|
## Tests
|
|
101
124
|
|
|
102
125
|
```bash
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { expect,
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
2
|
import { Memoize, MemoizeAsync } from "../src/index";
|
|
3
3
|
|
|
4
4
|
let addSyncCount = 0;
|
|
@@ -14,44 +14,91 @@ const addAsync = async (x: number, y: number) => {
|
|
|
14
14
|
return x + y;
|
|
15
15
|
};
|
|
16
16
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
expect(addCached(1, 2)).toBe(3);
|
|
23
|
-
expect(addCached(1, 2)).toBe(3);
|
|
24
|
-
expect(addCached(1, 2)).toBe(3);
|
|
17
|
+
const _asyncThrowError = MemoizeAsync(async (x: number, y: number) => {
|
|
18
|
+
addAsyncCount += 1;
|
|
19
|
+
throw new Error("Boom!");
|
|
20
|
+
return x + y;
|
|
21
|
+
});
|
|
25
22
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
23
|
+
const asyncThrowError = MemoizeAsync(async (x: number, y: number) => {
|
|
24
|
+
try {
|
|
25
|
+
await _asyncThrowError(x, y);
|
|
26
|
+
} catch {
|
|
27
|
+
return -1;
|
|
28
|
+
}
|
|
29
29
|
});
|
|
30
30
|
|
|
31
|
-
|
|
32
|
-
|
|
31
|
+
describe("Memoization", () => {
|
|
32
|
+
it("sync", async () => {
|
|
33
|
+
const addCached = Memoize(add);
|
|
33
34
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
35
|
+
expect(addCached(1, 2)).toBe(3);
|
|
36
|
+
expect(addCached(1, 2)).toBe(3);
|
|
37
|
+
expect(addCached(1, 2)).toBe(3);
|
|
38
|
+
expect(addCached(1, 2)).toBe(3);
|
|
39
|
+
expect(addCached(1, 2)).toBe(3);
|
|
39
40
|
|
|
40
41
|
// different key here
|
|
41
|
-
|
|
42
|
-
|
|
42
|
+
expect(addCached(2, 1)).toBe(3);
|
|
43
|
+
expect(addSyncCount).toBe(2);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it("async", async () => {
|
|
47
|
+
const addCachedAsync = MemoizeAsync(addAsync);
|
|
48
|
+
|
|
49
|
+
await Promise.all([
|
|
50
|
+
addCachedAsync(1, 2).then((value) => expect(value).toBe(3)),
|
|
51
|
+
addCachedAsync(1, 2).then((value) => expect(value).toBe(3)),
|
|
52
|
+
addCachedAsync(1, 2).then((value) => expect(value).toBe(3)),
|
|
53
|
+
addCachedAsync(1, 2).then((value) => expect(value).toBe(3)),
|
|
54
|
+
|
|
55
|
+
// different key here
|
|
56
|
+
addCachedAsync(2, 1).then((value) => expect(value).toBe(3)),
|
|
57
|
+
]);
|
|
43
58
|
|
|
44
|
-
|
|
45
|
-
|
|
59
|
+
expect(addAsyncCount).toBe(2);
|
|
60
|
+
expect(addCachedAsync.cache.size).toBe(2);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it("resolver", () => {
|
|
64
|
+
// This its the resolver function to ensure the same value is returned for
|
|
65
|
+
// the same key.
|
|
66
|
+
|
|
67
|
+
const addCachedSameKey = Memoize(add, { resolver: (x, y) => "key" });
|
|
68
|
+
|
|
69
|
+
expect(addCachedSameKey(5, 7)).toBe(12);
|
|
70
|
+
expect(addCachedSameKey(1, 1)).toBe(12);
|
|
71
|
+
expect(addCachedSameKey(5, 1)).toBe(12);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it("async error", async () => {
|
|
75
|
+
expect(await asyncThrowError(4, 3)).toBe(-1);
|
|
76
|
+
});
|
|
46
77
|
});
|
|
47
78
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
79
|
+
describe("Memoization of Class methods", () => {
|
|
80
|
+
class AddClass {
|
|
81
|
+
count: number = 0;
|
|
82
|
+
|
|
83
|
+
constructor() {
|
|
84
|
+
this.add = Memoize(this.add.bind(this));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
add(x: number, y: number) {
|
|
88
|
+
this.count += 1;
|
|
89
|
+
return x + y;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
51
92
|
|
|
52
|
-
|
|
93
|
+
it("Test1", () => {
|
|
94
|
+
const obj = new AddClass();
|
|
53
95
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
96
|
+
expect(obj.count).toBe(0);
|
|
97
|
+
expect(obj.add(1, 2)).toBe(3);
|
|
98
|
+
expect(obj.count).toBe(1);
|
|
99
|
+
expect(obj.add(1, 2)).toBe(3);
|
|
100
|
+
expect(obj.count).toBe(1);
|
|
101
|
+
expect(obj.add(5, 2)).toBe(7);
|
|
102
|
+
expect(obj.count).toBe(2);
|
|
103
|
+
});
|
|
57
104
|
});
|
package/lib/index.d.ts
CHANGED
|
@@ -14,7 +14,7 @@ declare const Memoize: <Args extends unknown[], Return>(cb: (...args: Args) => R
|
|
|
14
14
|
/**
|
|
15
15
|
* Memoize an asynchronous function.
|
|
16
16
|
*
|
|
17
|
-
* This differs from the
|
|
17
|
+
* This differs from the synchronous case by ensuring multiple calls with the
|
|
18
18
|
* same arguments is only evaluated once. This is controlled by using a
|
|
19
19
|
* semaphore, which forces redundant calls to wait until the first call
|
|
20
20
|
* completes.
|
package/lib/memoize.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memoize.cjs","sources":["../src/index.ts"],"sourcesContent":["import Semaphore from \"@chriscdn/promise-semaphore\";\nimport QuickLRU from \"quick-lru\";\n\nconst kDefaultMaxSize = 1000;\n\ntype Options<T extends any[]> = {\n
|
|
1
|
+
{"version":3,"file":"memoize.cjs","sources":["../src/index.ts"],"sourcesContent":["import Semaphore from \"@chriscdn/promise-semaphore\";\nimport QuickLRU from \"quick-lru\";\n\nconst kDefaultMaxSize = 1000;\n\ntype Options<T extends any[]> = {\n maxSize: number;\n maxAge?: number;\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>> = {},\n) => {\n const maxAge: number | undefined = options.maxAge;\n const maxSize = options.maxSize ?? kDefaultMaxSize;\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 cache.set(key, returnValue);\n return returnValue;\n }\n };\n\n memoizedFunction.cache = cache;\n\n return memoizedFunction;\n};\n\n/**\n * Memoize an asynchronous function.\n *\n * This differs from the synchronous case by ensuring multiple calls with the\n * same arguments is only evaluated once. This is controlled by using a\n * semaphore, which forces redundant calls to wait until the first call\n * completes.\n */\nconst MemoizeAsync = <Args extends unknown[], Return>(\n cb: (...args: Args) => Promise<Return>,\n options: Partial<Options<Args>> = {},\n) => {\n const maxAge: number | undefined = options.maxAge;\n const maxSize = options.maxSize ?? kDefaultMaxSize;\n\n const resolver =\n options.resolver ?? ((...args: Args) => JSON.stringify(args));\n\n const semaphore = new Semaphore();\n\n const cache = new QuickLRU<string, Return>({\n maxAge,\n maxSize,\n });\n\n const memoizedFunction = async (...args: Args): Promise<Return> => {\n const key = resolver(...args);\n\n if (cache.has(key)) {\n return cache.get(key)!;\n } else {\n try {\n await semaphore.acquire(key);\n\n if (cache.has(key)) {\n return cache.get(key);\n } else {\n const returnValue = await cb(...args);\n cache.set(key, returnValue);\n return returnValue;\n }\n } finally {\n semaphore.release(key);\n }\n }\n };\n\n memoizedFunction.cache = cache;\n\n return memoizedFunction;\n};\n\nexport { Memoize, MemoizeAsync };\n"],"names":["cb","options","_options$maxSize","_options$resolver","maxSize","resolver","JSON","stringify","slice","call","arguments","cache","QuickLRU","maxAge","memoizedFunction","args","key","apply","has","get","returnValue","set","_options$maxSize2","_options$resolver2","semaphore","Semaphore","_arguments","Promise","resolve","acquire","then","_finallyRethrows","_wasThrown","_result","release","e","reject"],"mappings":"wMAcgB,SACdA,EACAC,GACEC,IAAAA,EAAAC,OADFF,IAAAA,IAAAA,EAAkC,CAAA,GAElC,IACMG,EAAyB,OAAlBF,EAAGD,EAAQG,SAAOF,EAhBT,IAkBhBG,EACY,OADJF,EACZF,EAAQI,UAAQF,EAAK,WAAmB,OAAAG,KAAKC,UAAS,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EAAA,OAAAA,CAAA,GAG7B,CAAC,MAAAE,GAAA,OAAAR,QAAAS,OAAAD,EAEDrB,CAAAA,EAEA,OAFAA,EAAiBH,MAAQA,EAElBG,CACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memoize.modern.js","sources":["../src/index.ts"],"sourcesContent":["import Semaphore from \"@chriscdn/promise-semaphore\";\nimport QuickLRU from \"quick-lru\";\n\nconst kDefaultMaxSize = 1000;\n\ntype Options<T extends any[]> = {\n
|
|
1
|
+
{"version":3,"file":"memoize.modern.js","sources":["../src/index.ts"],"sourcesContent":["import Semaphore from \"@chriscdn/promise-semaphore\";\nimport QuickLRU from \"quick-lru\";\n\nconst kDefaultMaxSize = 1000;\n\ntype Options<T extends any[]> = {\n maxSize: number;\n maxAge?: number;\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>> = {},\n) => {\n const maxAge: number | undefined = options.maxAge;\n const maxSize = options.maxSize ?? kDefaultMaxSize;\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 cache.set(key, returnValue);\n return returnValue;\n }\n };\n\n memoizedFunction.cache = cache;\n\n return memoizedFunction;\n};\n\n/**\n * Memoize an asynchronous function.\n *\n * This differs from the synchronous case by ensuring multiple calls with the\n * same arguments is only evaluated once. This is controlled by using a\n * semaphore, which forces redundant calls to wait until the first call\n * completes.\n */\nconst MemoizeAsync = <Args extends unknown[], Return>(\n cb: (...args: Args) => Promise<Return>,\n options: Partial<Options<Args>> = {},\n) => {\n const maxAge: number | undefined = options.maxAge;\n const maxSize = options.maxSize ?? kDefaultMaxSize;\n\n const resolver =\n options.resolver ?? ((...args: Args) => JSON.stringify(args));\n\n const semaphore = new Semaphore();\n\n const cache = new QuickLRU<string, Return>({\n maxAge,\n maxSize,\n });\n\n const memoizedFunction = async (...args: Args): Promise<Return> => {\n const key = resolver(...args);\n\n if (cache.has(key)) {\n return cache.get(key)!;\n } else {\n try {\n await semaphore.acquire(key);\n\n if (cache.has(key)) {\n return cache.get(key);\n } else {\n const returnValue = await cb(...args);\n cache.set(key, returnValue);\n return returnValue;\n }\n } finally {\n semaphore.release(key);\n }\n }\n };\n\n memoizedFunction.cache = cache;\n\n return memoizedFunction;\n};\n\nexport { Memoize, MemoizeAsync };\n"],"names":["Memoize","cb","options","_options$maxSize","_options$resolver","maxSize","resolver","args","JSON","stringify","cache","QuickLRU","maxAge","memoizedFunction","key","has","get","returnValue","set","MemoizeAsync","_options$maxSize2","_options$resolver2","semaphore","Semaphore","async","acquire","release"],"mappings":"oEAGA,MAWMA,EAAUA,CACdC,EACAC,EAAkC,CAAA,KAChC,IAAAC,EAAAC,EACF,MACMC,SAAOF,EAAGD,EAAQG,SAAOF,EAhBT,IAkBhBG,EACY,OADJF,EACZF,EAAQI,UAAQF,EAAK,IAAIG,IAAeC,KAAKC,UAAUF,GAEnDG,EAAQ,IAAIC,EAAyB,CACzCC,OAPiCV,EAAQU,OAQzCP,YAGIQ,EAAmBA,IAAIN,KAC3B,MAAMO,EAAMR,KAAYC,GAExB,GAAIG,EAAMK,IAAID,GACZ,OAAOJ,EAAMM,IAAIF,GACZ,CACL,MAAMG,EAAchB,KAAMM,GAE1B,OADAG,EAAMQ,IAAIJ,EAAKG,GACRA,CACR,GAKH,OAFAJ,EAAiBH,MAAQA,EAElBG,GAWHM,EAAeA,CACnBlB,EACAC,EAAkC,CAAA,KAChC,IAAAkB,EAAAC,EACF,MAAMT,EAA6BV,EAAQU,OACrCP,EAAyBe,OAAlBA,EAAGlB,EAAQG,SAAOe,EAxDT,IA0DhBd,SAAQe,EACZnB,EAAQI,UAAQe,EAAK,IAAId,IAAeC,KAAKC,UAAUF,GAEnDe,EAAY,IAAIC,EAEhBb,EAAQ,IAAIC,EAAyB,CACzCC,SACAP,YAGIQ,EAAmBW,SAAUjB,KACjC,MAAMO,EAAMR,KAAYC,GAExB,GAAIG,EAAMK,IAAID,GACZ,OAAOJ,EAAMM,IAAIF,GAEjB,IAGE,SAFMQ,EAAUG,QAAQX,GAEpBJ,EAAMK,IAAID,GACZ,OAAOJ,EAAMM,IAAIF,GACZ,CACL,MAAMG,QAAoBhB,KAAMM,GAEhC,OADAG,EAAMQ,IAAIJ,EAAKG,GACRA,CACR,CACF,CAAA,QACCK,EAAUI,QAAQZ,EACnB,CACF,EAKH,OAFAD,EAAiBH,MAAQA,EAElBG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memoize.module.js","sources":["../src/index.ts"],"sourcesContent":["import Semaphore from \"@chriscdn/promise-semaphore\";\nimport QuickLRU from \"quick-lru\";\n\nconst kDefaultMaxSize = 1000;\n\ntype Options<T extends any[]> = {\n
|
|
1
|
+
{"version":3,"file":"memoize.module.js","sources":["../src/index.ts"],"sourcesContent":["import Semaphore from \"@chriscdn/promise-semaphore\";\nimport QuickLRU from \"quick-lru\";\n\nconst kDefaultMaxSize = 1000;\n\ntype Options<T extends any[]> = {\n maxSize: number;\n maxAge?: number;\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>> = {},\n) => {\n const maxAge: number | undefined = options.maxAge;\n const maxSize = options.maxSize ?? kDefaultMaxSize;\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 cache.set(key, returnValue);\n return returnValue;\n }\n };\n\n memoizedFunction.cache = cache;\n\n return memoizedFunction;\n};\n\n/**\n * Memoize an asynchronous function.\n *\n * This differs from the synchronous case by ensuring multiple calls with the\n * same arguments is only evaluated once. This is controlled by using a\n * semaphore, which forces redundant calls to wait until the first call\n * completes.\n */\nconst MemoizeAsync = <Args extends unknown[], Return>(\n cb: (...args: Args) => Promise<Return>,\n options: Partial<Options<Args>> = {},\n) => {\n const maxAge: number | undefined = options.maxAge;\n const maxSize = options.maxSize ?? kDefaultMaxSize;\n\n const resolver =\n options.resolver ?? ((...args: Args) => JSON.stringify(args));\n\n const semaphore = new Semaphore();\n\n const cache = new QuickLRU<string, Return>({\n maxAge,\n maxSize,\n });\n\n const memoizedFunction = async (...args: Args): Promise<Return> => {\n const key = resolver(...args);\n\n if (cache.has(key)) {\n return cache.get(key)!;\n } else {\n try {\n await semaphore.acquire(key);\n\n if (cache.has(key)) {\n return cache.get(key);\n } else {\n const returnValue = await cb(...args);\n cache.set(key, returnValue);\n return returnValue;\n }\n } finally {\n semaphore.release(key);\n }\n }\n };\n\n memoizedFunction.cache = cache;\n\n return memoizedFunction;\n};\n\nexport { Memoize, MemoizeAsync };\n"],"names":["Memoize","cb","options","_options$maxSize","_options$resolver","maxSize","resolver","JSON","stringify","slice","call","arguments","cache","QuickLRU","maxAge","memoizedFunction","args","key","apply","has","get","returnValue","set","MemoizeAsync","_options$maxSize2","_options$resolver2","semaphore","Semaphore","_arguments","Promise","resolve","acquire","then","_finallyRethrows","_wasThrown","_result","release","e","reject"],"mappings":"oEAGA,IAWMA,EAAU,SACdC,EACAC,GACEC,IAAAA,EAAAC,OADFF,IAAAA,IAAAA,EAAkC,CAAA,GAElC,IACMG,EAAyB,OAAlBF,EAAGD,EAAQG,SAAOF,EAhBT,IAkBhBG,EACY,OADJF,EACZF,EAAQI,UAAQF,EAAK,WAAmB,OAAAG,KAAKC,UAAS,GAAAC,MAAAC,KAAAC,WAAM,EAExDC,EAAQ,IAAIC,EAAyB,CACzCC,OAPiCZ,EAAQY,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AA,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.5",
|
|
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,11 @@
|
|
|
22
22
|
"test": "vitest"
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@chriscdn/promise-semaphore": "^2.0.
|
|
25
|
+
"@chriscdn/promise-semaphore": "^2.0.10",
|
|
26
26
|
"quick-lru": "^7.0.0"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"microbundle": "^0.15.1",
|
|
30
|
-
"vitest": "^
|
|
30
|
+
"vitest": "^3.0.7"
|
|
31
31
|
}
|
|
32
32
|
}
|
package/src/index.ts
CHANGED
|
@@ -4,96 +4,96 @@ import QuickLRU from "quick-lru";
|
|
|
4
4
|
const kDefaultMaxSize = 1000;
|
|
5
5
|
|
|
6
6
|
type Options<T extends any[]> = {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
7
|
+
maxSize: number;
|
|
8
|
+
maxAge?: number;
|
|
9
|
+
resolver: (...args: T) => string;
|
|
10
10
|
};
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* Memoize a synchronous function.
|
|
14
14
|
*/
|
|
15
15
|
const Memoize = <Args extends unknown[], Return>(
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
cb: (...args: Args) => Return,
|
|
17
|
+
options: Partial<Options<Args>> = {},
|
|
18
18
|
) => {
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
const maxAge: number | undefined = options.maxAge;
|
|
20
|
+
const maxSize = options.maxSize ?? kDefaultMaxSize;
|
|
21
21
|
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
const resolver =
|
|
23
|
+
options.resolver ?? ((...args: Args) => JSON.stringify(args));
|
|
24
24
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
25
|
+
const cache = new QuickLRU<string, Return>({
|
|
26
|
+
maxAge,
|
|
27
|
+
maxSize,
|
|
28
|
+
});
|
|
29
29
|
|
|
30
|
-
|
|
31
|
-
|
|
30
|
+
const memoizedFunction = (...args: Args): Return => {
|
|
31
|
+
const key = resolver(...args);
|
|
32
32
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
33
|
+
if (cache.has(key)) {
|
|
34
|
+
return cache.get(key);
|
|
35
|
+
} else {
|
|
36
|
+
const returnValue = cb(...args);
|
|
37
|
+
cache.set(key, returnValue);
|
|
38
|
+
return returnValue;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
41
|
|
|
42
|
-
|
|
42
|
+
memoizedFunction.cache = cache;
|
|
43
43
|
|
|
44
|
-
|
|
44
|
+
return memoizedFunction;
|
|
45
45
|
};
|
|
46
46
|
|
|
47
47
|
/**
|
|
48
48
|
* Memoize an asynchronous function.
|
|
49
49
|
*
|
|
50
|
-
* This differs from the
|
|
50
|
+
* This differs from the synchronous case by ensuring multiple calls with the
|
|
51
51
|
* same arguments is only evaluated once. This is controlled by using a
|
|
52
52
|
* semaphore, which forces redundant calls to wait until the first call
|
|
53
53
|
* completes.
|
|
54
54
|
*/
|
|
55
55
|
const MemoizeAsync = <Args extends unknown[], Return>(
|
|
56
|
-
|
|
57
|
-
|
|
56
|
+
cb: (...args: Args) => Promise<Return>,
|
|
57
|
+
options: Partial<Options<Args>> = {},
|
|
58
58
|
) => {
|
|
59
|
-
|
|
60
|
-
|
|
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));
|
|
61
64
|
|
|
62
|
-
|
|
63
|
-
((...args: Args) => JSON.stringify(args));
|
|
65
|
+
const semaphore = new Semaphore();
|
|
64
66
|
|
|
65
|
-
|
|
67
|
+
const cache = new QuickLRU<string, Return>({
|
|
68
|
+
maxAge,
|
|
69
|
+
maxSize,
|
|
70
|
+
});
|
|
66
71
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
maxSize,
|
|
70
|
-
});
|
|
72
|
+
const memoizedFunction = async (...args: Args): Promise<Return> => {
|
|
73
|
+
const key = resolver(...args);
|
|
71
74
|
|
|
72
|
-
|
|
73
|
-
|
|
75
|
+
if (cache.has(key)) {
|
|
76
|
+
return cache.get(key)!;
|
|
77
|
+
} else {
|
|
78
|
+
try {
|
|
79
|
+
await semaphore.acquire(key);
|
|
74
80
|
|
|
75
81
|
if (cache.has(key)) {
|
|
76
|
-
|
|
82
|
+
return cache.get(key);
|
|
77
83
|
} else {
|
|
78
|
-
|
|
79
|
-
|
|
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
|
-
}
|
|
84
|
+
const returnValue = await cb(...args);
|
|
85
|
+
cache.set(key, returnValue);
|
|
86
|
+
return returnValue;
|
|
91
87
|
}
|
|
92
|
-
|
|
88
|
+
} finally {
|
|
89
|
+
semaphore.release(key);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
93
|
|
|
94
|
-
|
|
94
|
+
memoizedFunction.cache = cache;
|
|
95
95
|
|
|
96
|
-
|
|
96
|
+
return memoizedFunction;
|
|
97
97
|
};
|
|
98
98
|
|
|
99
99
|
export { Memoize, MemoizeAsync };
|