@chriscdn/memoize 1.0.7 → 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 +12 -15
- package/__tests__/memoize.test.ts +35 -0
- package/lib/index.d.ts +1 -13
- 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 +2 -55
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,26 +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 whether to add the returnValue to the cache.
|
|
87
|
+
// A synchronous function that returns `true` or `false` to determine whether to add the returnValue to the cache.
|
|
91
88
|
shouldCache: (returnValue: Return, key: string) => true,
|
|
92
89
|
|
|
93
|
-
// A synchronous function to generate cache
|
|
90
|
+
// A synchronous function to generate a cache key (must return a string).
|
|
94
91
|
resolver: (...args) => JSON.stringify(args),
|
|
95
92
|
};
|
|
96
93
|
```
|
|
@@ -100,7 +97,7 @@ const options = {
|
|
|
100
97
|
The underlying [quick-lru](https://www.npmjs.com/package/quick-lru) instance is accessible via the `.cache` property on the memoized function:
|
|
101
98
|
|
|
102
99
|
```ts
|
|
103
|
-
const add =
|
|
100
|
+
const add = Memoize(_add);
|
|
104
101
|
const result = await add(5, 7);
|
|
105
102
|
|
|
106
103
|
console.log(add.cache.size === 1);
|
|
@@ -161,3 +161,38 @@ describe("ShouldCache", () => {
|
|
|
161
161
|
expect(myFunction.cache.has(doNotCache)).toBe(false);
|
|
162
162
|
});
|
|
163
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
|
@@ -12,16 +12,4 @@ declare const Memoize: <Args extends unknown[], Return>(cb: (...args: Args) => R
|
|
|
12
12
|
(...args: Args): Return;
|
|
13
13
|
cache: QuickLRU<string, Return>;
|
|
14
14
|
};
|
|
15
|
-
|
|
16
|
-
* Memoize an asynchronous function.
|
|
17
|
-
*
|
|
18
|
-
* This differs from the synchronous case by ensuring multiple calls with the
|
|
19
|
-
* same arguments is only evaluated once. This is controlled by using a
|
|
20
|
-
* semaphore, which forces redundant calls to wait until the first call
|
|
21
|
-
* completes.
|
|
22
|
-
*/
|
|
23
|
-
declare const MemoizeAsync: <Args extends unknown[], Return>(cb: (...args: Args) => Promise<Return>, options?: Partial<Options<Args, Return>>) => {
|
|
24
|
-
(...args: Args): Promise<Return>;
|
|
25
|
-
cache: QuickLRU<string, Return>;
|
|
26
|
-
};
|
|
27
|
-
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,4 +1,3 @@
|
|
|
1
|
-
import Semaphore from "@chriscdn/promise-semaphore";
|
|
2
1
|
import QuickLRU from "quick-lru";
|
|
3
2
|
|
|
4
3
|
const kDefaultMaxSize = 1000;
|
|
@@ -49,60 +48,8 @@ const Memoize = <Args extends unknown[], Return>(
|
|
|
49
48
|
};
|
|
50
49
|
|
|
51
50
|
/**
|
|
52
|
-
* Memoize
|
|
53
|
-
*
|
|
54
|
-
* This differs from the synchronous case by ensuring multiple calls with the
|
|
55
|
-
* same arguments is only evaluated once. This is controlled by using a
|
|
56
|
-
* semaphore, which forces redundant calls to wait until the first call
|
|
57
|
-
* completes.
|
|
51
|
+
* @deprecated `Memoize` can be used for asynchronous functions.
|
|
58
52
|
*/
|
|
59
|
-
const MemoizeAsync =
|
|
60
|
-
cb: (...args: Args) => Promise<Return>,
|
|
61
|
-
options: Partial<Options<Args, Return>> = {},
|
|
62
|
-
) => {
|
|
63
|
-
const maxAge: number | undefined = options.maxAge;
|
|
64
|
-
const maxSize = options.maxSize ?? kDefaultMaxSize;
|
|
65
|
-
const shouldCache = options.shouldCache ?? (() => true);
|
|
66
|
-
|
|
67
|
-
const resolver =
|
|
68
|
-
options.resolver ?? ((...args: Args) => JSON.stringify(args));
|
|
69
|
-
|
|
70
|
-
const semaphore = new Semaphore();
|
|
71
|
-
|
|
72
|
-
const cache = new QuickLRU<string, Return>({
|
|
73
|
-
maxAge,
|
|
74
|
-
maxSize,
|
|
75
|
-
});
|
|
76
|
-
|
|
77
|
-
const memoizedFunction = async (...args: Args): Promise<Return> => {
|
|
78
|
-
const key = resolver(...args);
|
|
79
|
-
|
|
80
|
-
if (cache.has(key)) {
|
|
81
|
-
return cache.get(key)!;
|
|
82
|
-
} else {
|
|
83
|
-
try {
|
|
84
|
-
await semaphore.acquire(key);
|
|
85
|
-
|
|
86
|
-
if (cache.has(key)) {
|
|
87
|
-
return cache.get(key);
|
|
88
|
-
} else {
|
|
89
|
-
const returnValue = await cb(...args);
|
|
90
|
-
|
|
91
|
-
if (shouldCache(returnValue, key)) {
|
|
92
|
-
cache.set(key, returnValue);
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
return returnValue;
|
|
96
|
-
}
|
|
97
|
-
} finally {
|
|
98
|
-
semaphore.release(key);
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
};
|
|
102
|
-
|
|
103
|
-
memoizedFunction.cache = cache;
|
|
104
|
-
|
|
105
|
-
return memoizedFunction;
|
|
106
|
-
};
|
|
53
|
+
const MemoizeAsync = Memoize;
|
|
107
54
|
|
|
108
55
|
export { Memoize, MemoizeAsync };
|