@chriscdn/memoize 1.0.9 → 1.0.11
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 +8 -0
- package/lib/index.d.ts +3 -3
- 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 +8 -4
- package/__tests__/memoize.test.ts +0 -201
- package/src/index.ts +0 -55
package/README.md
CHANGED
|
@@ -92,6 +92,14 @@ const options = {
|
|
|
92
92
|
};
|
|
93
93
|
```
|
|
94
94
|
|
|
95
|
+
**Note**: `Memoize` works with both _synchronous_ and _asynchronous_ functions. However, when using the `shouldCache` callback with an asynchronous function, the `returnValue` passed to `shouldCache` is a `Promise`. This is effectively useless since caching decisions should be based on the resolved value.
|
|
96
|
+
|
|
97
|
+
To address this, use `MemoizeAsync` instead. It has the same interface as `Memoize`, but works with asynchronous functions and passes the resolved value to `shouldCache`.
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import { MemoizeAsync } from "@chriscdn/memoize";
|
|
101
|
+
```
|
|
102
|
+
|
|
95
103
|
## Cache
|
|
96
104
|
|
|
97
105
|
The underlying [quick-lru](https://www.npmjs.com/package/quick-lru) instance is accessible via the `.cache` property on the memoized function:
|
package/lib/index.d.ts
CHANGED
|
@@ -13,10 +13,10 @@ declare const Memoize: <Args extends unknown[], Return>(cb: (...args: Args) => R
|
|
|
13
13
|
cache: QuickLRU<string, Return>;
|
|
14
14
|
};
|
|
15
15
|
/**
|
|
16
|
-
*
|
|
16
|
+
* Memoize an asynchronous function.
|
|
17
17
|
*/
|
|
18
|
-
declare const MemoizeAsync: <Args extends unknown[], Return>(cb: (...args: Args) => Return
|
|
19
|
-
(...args: Args): Return
|
|
18
|
+
declare const MemoizeAsync: <Args extends unknown[], Return>(cb: (...args: Args) => Promise<Return>, options?: Partial<Options<Args, Return>>) => {
|
|
19
|
+
(...args: Args): Promise<Return>;
|
|
20
20
|
cache: QuickLRU<string, Return>;
|
|
21
21
|
};
|
|
22
22
|
export { Memoize, MemoizeAsync };
|
package/lib/memoize.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
var e=require("@chriscdn/promise-semaphore");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=/*#__PURE__*/r(require("quick-lru"));exports.Memoize=function(e,r){var t,i,u;void 0===r&&(r={});var l=null!=(t=r.maxSize)?t:1e3,a=null!=(i=r.shouldCache)?i:function(){return!0},o=null!=(u=r.resolver)?u:function(){return JSON.stringify([].slice.call(arguments))},c=new n.default({maxAge:r.maxAge,maxSize:l}),s=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 s.cache=c,s},exports.MemoizeAsync=function(r,t){var i,u,l;void 0===t&&(t={});var a=null!=(i=t.maxSize)?i:1e3,o=null!=(u=t.shouldCache)?u:function(){return!0},c=null!=(l=t.resolver)?l:function(){return JSON.stringify([].slice.call(arguments))},s=new n.default({maxAge:t.maxAge,maxSize:a}),f=new e.Semaphore,v=function(){try{var e=[].slice.call(arguments),n=c.apply(void 0,e);return Promise.resolve(function(t,i){try{var u=Promise.resolve(f.acquire(n)).then(function(){return s.has(n)?s.get(n):Promise.resolve(r.apply(void 0,e)).then(function(e){return o(e,n)&&s.set(n,e),e})})}catch(e){return i(!0,e)}return u&&u.then?u.then(i.bind(null,!1),i.bind(null,!0)):i(!1,u)}(0,function(e,r){if(f.release(n),e)throw r;return r}))}catch(e){return Promise.reject(e)}};return v.cache=s,v};
|
|
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 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 = options.resolver ??\n ((...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) as Return;\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\n/**\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[], 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 = options.resolver ??\n ((...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) as Return;\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\n/**\n * Memoize an asynchronous function.\n */\nconst MemoizeAsync = <Args extends unknown[], Return>(\n cb: (...args: Args) => Promise<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 = options.resolver ??\n ((...args: Args) => JSON.stringify(args));\n\n const cache = new QuickLRU<string, Return>({\n maxAge,\n maxSize,\n });\n\n const semaphore = new Semaphore();\n\n const memoizedFunction = async (...args: Args): Promise<Return> => {\n const key = resolver(...args);\n\n try {\n await semaphore.acquire(key);\n\n if (cache.has(key)) {\n return cache.get(key) as Return;\n } else {\n const returnValue = await cb(...args);\n if (shouldCache(returnValue, key)) {\n cache.set(key, returnValue);\n }\n return returnValue;\n }\n } finally {\n semaphore.release(key);\n }\n };\n\n memoizedFunction.cache = cache;\n\n return memoizedFunction;\n};\n\nexport { Memoize, MemoizeAsync };\n"],"names":["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","_options$maxSize2","_options$shouldCache2","_options$resolver2","semaphore","Semaphore","_arguments","Promise","resolve","acquire","then","_finallyRethrows","_wasThrown","_result","release","e","reject"],"mappings":"gLAegB,SACdA,EACAC,GACEC,IAAAA,EAAAC,EAAAC,WADFH,IAAAA,EAA0C,CAAE,GAE5C,IACMI,EAAyBH,OAAlBA,EAAGD,EAAQI,SAAOH,EAjBT,IAkBhBI,EAAiC,OAAtBH,EAAGF,EAAQK,aAAWH,EAAK,WAAM,OAAA,CAAI,EAEhDI,SAAQH,EAAGH,EAAQM,UAAQH,EAC9B,WAAmB,OAAAI,KAAKC,UAAS,GAAAC,MAAAC,KAAAC,WAAM,EAEpCC,EAAQ,IAAIC,EAAAA,QAAyB,CACzCC,OARiCd,EAAQc,OASzCV,QAAAA,IAGIW,EAAmB,WAAI,IAAAC,EAAU,GAAAP,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,uBAKqB,SACnBhB,EACAC,GACEuB,IAAAA,EAAAC,EAAAC,OADwC,IAA1CzB,IAAAA,EAA0C,CAAA,GAE1C,IACMI,EAAyBmB,OAAlBA,EAAGvB,EAAQI,SAAOmB,EAvDT,IAwDhBlB,EAAiCmB,OAAtBA,EAAGxB,EAAQK,aAAWmB,EAAK,WAAA,OAAU,CAAA,EAEhDlB,EAA2B,OAAnBmB,EAAGzB,EAAQM,UAAQmB,EAC9B,WAAmB,OAAAlB,KAAKC,UAASC,GAAAA,MAAAC,KAAAC,WAAM,EAEpCC,EAAQ,IAAIC,EAAQ,QAAiB,CACzCC,OARiCd,EAAQc,OASzCV,QAAAA,IAGIsB,EAAY,IAAIC,EAAAA,UAEhBZ,EAAA,eAA4Da,IAA/BZ,EAAU,GAAAP,MAAAC,KAAqBC,WAC1DM,EAAMX,EAAQY,WAAIF,EAAAA,GAAM,OAAAa,QAAAC,gCAE1BD,QAAAC,QACIJ,EAAUK,QAAQd,IAAIe,KAAA,WAAA,OAExBpB,EAAMO,IAAIF,GACLL,EAAMQ,IAAIH,GAAeY,QAAAC,QAEN/B,EAAEmB,WAAA,EAAIF,IAAKgB,KAAA,SAA/BX,GAIN,OAHIhB,EAAYgB,EAAaJ,IAC3BL,EAAMU,IAAIL,EAAKI,GAEVA,CAAY,EAEtB,4FAd6BY,CAAA,EAc7BC,SAAAA,EAAAC,GACwB,GAAvBT,EAAUU,QAAQnB,GAAKiB,EAAA,MAAAC,EAAAA,OAAAA,CAAA,GAE3B,CAAC,MAAAE,GAAAR,OAAAA,QAAAS,OAAAD,EAAA,CAAA,EAID,OAFAtB,EAAiBH,MAAQA,EAElBG,CACT"}
|
package/lib/memoize.modern.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"quick-lru";const
|
|
1
|
+
import{Semaphore as e}from"@chriscdn/promise-semaphore";import r from"quick-lru";const n=(e,n={})=>{var a,t,s;const l=null!=(a=n.maxSize)?a:1e3,i=null!=(t=n.shouldCache)?t:()=>!0,c=null!=(s=n.resolver)?s:(...e)=>JSON.stringify(e),o=new r({maxAge:n.maxAge,maxSize:l}),u=(...r)=>{const n=c(...r);if(o.has(n))return o.get(n);{const a=e(...r);return i(a,n)&&o.set(n,a),a}};return u.cache=o,u},a=(n,a={})=>{var t,s,l;const i=null!=(t=a.maxSize)?t:1e3,c=null!=(s=a.shouldCache)?s:()=>!0,o=null!=(l=a.resolver)?l:(...e)=>JSON.stringify(e),u=new r({maxAge:a.maxAge,maxSize:i}),m=new e,h=async(...e)=>{const r=o(...e);try{if(await m.acquire(r),u.has(r))return u.get(r);{const a=await n(...e);return c(a,r)&&u.set(r,a),a}}finally{m.release(r)}};return h.cache=u,h};export{n as Memoize,a as MemoizeAsync};
|
|
2
2
|
//# sourceMappingURL=memoize.modern.js.map
|
|
@@ -1 +1 @@
|
|
|
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 = options.resolver ??\n ((...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) as Return;\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\n/**\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[], 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 = options.resolver ??\n ((...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) as Return;\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\n/**\n * Memoize an asynchronous function.\n */\nconst MemoizeAsync = <Args extends unknown[], Return>(\n cb: (...args: Args) => Promise<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 = options.resolver ??\n ((...args: Args) => JSON.stringify(args));\n\n const cache = new QuickLRU<string, Return>({\n maxAge,\n maxSize,\n });\n\n const semaphore = new Semaphore();\n\n const memoizedFunction = async (...args: Args): Promise<Return> => {\n const key = resolver(...args);\n\n try {\n await semaphore.acquire(key);\n\n if (cache.has(key)) {\n return cache.get(key) as Return;\n } else {\n const returnValue = await cb(...args);\n if (shouldCache(returnValue, key)) {\n cache.set(key, returnValue);\n }\n return returnValue;\n }\n } finally {\n semaphore.release(key);\n }\n };\n\n memoizedFunction.cache = cache;\n\n return memoizedFunction;\n};\n\nexport { Memoize, 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","MemoizeAsync","_options$maxSize2","_options$shouldCache2","_options$resolver2","semaphore","Semaphore","async","acquire","release"],"mappings":"iFAGA,MAYMA,EAAUA,CACdC,EACAC,EAA0C,MACxC,IAAAC,EAAAC,EAAAC,EACF,MACMC,SAAOH,EAAGD,EAAQI,SAAOH,EAjBT,IAkBhBI,EAAiC,OAAtBH,EAAGF,EAAQK,aAAWH,EAAK,KAAM,EAE5CI,EAA2BH,OAAnBA,EAAGH,EAAQM,UAAQH,EAC9B,IAAII,IAAeC,KAAKC,UAAUF,GAE/BG,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,GAMHM,EAAeA,CACnBpB,EACAC,EAA0C,CAAE,SAC1CoB,EAAAC,EAAAC,EACF,MACMlB,EAAyB,OAAlBgB,EAAGpB,EAAQI,SAAOgB,EAvDT,IAwDhBf,SAAWgB,EAAGrB,EAAQK,aAAWgB,EAAK,KAAM,EAE5Cf,EAA2B,OAAnBgB,EAAGtB,EAAQM,UAAQgB,EAC9B,IAAIf,IAAeC,KAAKC,UAAUF,GAE/BG,EAAQ,IAAIC,EAAyB,CACzCC,OARiCZ,EAAQY,OASzCR,YAGImB,EAAY,IAAIC,EAEhBX,EAAmBY,SAAUlB,KACjC,MAAMO,EAAMR,KAAYC,GAExB,IAGE,SAFMgB,EAAUG,QAAQZ,GAEpBJ,EAAMK,IAAID,GACZ,OAAOJ,EAAMM,IAAIF,GACZ,CACL,MAAMG,QAAoBlB,KAAMQ,GAIhC,OAHIF,EAAYY,EAAaH,IAC3BJ,EAAMQ,IAAIJ,EAAKG,GAEVA,CACR,CACF,CAAA,QACCM,EAAUI,QAAQb,EACnB,GAKH,OAFAD,EAAiBH,MAAQA,EAElBG"}
|
package/lib/memoize.module.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import r from"quick-lru";var
|
|
1
|
+
import{Semaphore as e}from"@chriscdn/promise-semaphore";import r from"quick-lru";var n=function(e,n){var t,i,l;void 0===n&&(n={});var u=null!=(t=n.maxSize)?t:1e3,o=null!=(i=n.shouldCache)?i:function(){return!0},a=null!=(l=n.resolver)?l:function(){return JSON.stringify([].slice.call(arguments))},c=new r({maxAge:n.maxAge,maxSize:u}),s=function(){var r=[].slice.call(arguments),n=a.apply(void 0,r);if(c.has(n))return c.get(n);var t=e.apply(void 0,r);return o(t,n)&&c.set(n,t),t};return s.cache=c,s},t=function(n,t){var i,l,u;void 0===t&&(t={});var o=null!=(i=t.maxSize)?i:1e3,a=null!=(l=t.shouldCache)?l:function(){return!0},c=null!=(u=t.resolver)?u:function(){return JSON.stringify([].slice.call(arguments))},s=new r({maxAge:t.maxAge,maxSize:o}),v=new e,f=function(){try{var e=[].slice.call(arguments),r=c.apply(void 0,e);return Promise.resolve(function(t,i){try{var l=Promise.resolve(v.acquire(r)).then(function(){return s.has(r)?s.get(r):Promise.resolve(n.apply(void 0,e)).then(function(e){return a(e,r)&&s.set(r,e),e})})}catch(e){return i(!0,e)}return l&&l.then?l.then(i.bind(null,!1),i.bind(null,!0)):i(!1,l)}(0,function(e,n){if(v.release(r),e)throw n;return n}))}catch(e){return Promise.reject(e)}};return f.cache=s,f};export{n as Memoize,t as MemoizeAsync};
|
|
2
2
|
//# sourceMappingURL=memoize.module.js.map
|
|
@@ -1 +1 @@
|
|
|
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 = options.resolver ??\n ((...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) as Return;\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\n/**\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[], 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 = options.resolver ??\n ((...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) as Return;\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\n/**\n * Memoize an asynchronous function.\n */\nconst MemoizeAsync = <Args extends unknown[], Return>(\n cb: (...args: Args) => Promise<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 = options.resolver ??\n ((...args: Args) => JSON.stringify(args));\n\n const cache = new QuickLRU<string, Return>({\n maxAge,\n maxSize,\n });\n\n const semaphore = new Semaphore();\n\n const memoizedFunction = async (...args: Args): Promise<Return> => {\n const key = resolver(...args);\n\n try {\n await semaphore.acquire(key);\n\n if (cache.has(key)) {\n return cache.get(key) as Return;\n } else {\n const returnValue = await cb(...args);\n if (shouldCache(returnValue, key)) {\n cache.set(key, returnValue);\n }\n return returnValue;\n }\n } finally {\n semaphore.release(key);\n }\n };\n\n memoizedFunction.cache = cache;\n\n return memoizedFunction;\n};\n\nexport { Memoize, 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","MemoizeAsync","_options$maxSize2","_options$shouldCache2","_options$resolver2","semaphore","Semaphore","_arguments","Promise","resolve","acquire","then","_finallyRethrows","_wasThrown","_result","release","e","reject"],"mappings":"iFAGA,IAYMA,EAAU,SACdC,EACAC,GACEC,IAAAA,EAAAC,EAAAC,WADFH,IAAAA,EAA0C,CAAE,GAE5C,IACMI,EAAyBH,OAAlBA,EAAGD,EAAQI,SAAOH,EAjBT,IAkBhBI,EAAiC,OAAtBH,EAAGF,EAAQK,aAAWH,EAAK,WAAM,OAAA,CAAI,EAEhDI,SAAQH,EAAGH,EAAQM,UAAQH,EAC9B,WAAmB,OAAAI,KAAKC,UAAS,GAAAC,MAAAC,KAAAC,WAAM,EAEpCC,EAAQ,IAAIC,EAAyB,CACzCC,OARiCd,EAAQc,OASzCV,QAAAA,IAGIW,EAAmB,WAAI,IAAAC,EAAU,GAAAP,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,EAKMQ,EAAe,SACnBxB,EACAC,GACEwB,IAAAA,EAAAC,EAAAC,OADwC,IAA1C1B,IAAAA,EAA0C,CAAA,GAE1C,IACMI,EAAyBoB,OAAlBA,EAAGxB,EAAQI,SAAOoB,EAvDT,IAwDhBnB,EAAiCoB,OAAtBA,EAAGzB,EAAQK,aAAWoB,EAAK,WAAA,OAAU,CAAA,EAEhDnB,EAA2B,OAAnBoB,EAAG1B,EAAQM,UAAQoB,EAC9B,WAAmB,OAAAnB,KAAKC,UAASC,GAAAA,MAAAC,KAAAC,WAAM,EAEpCC,EAAQ,IAAIC,EAAyB,CACzCC,OARiCd,EAAQc,OASzCV,QAAAA,IAGIuB,EAAY,IAAIC,EAEhBb,EAAA,eAA4Dc,IAA/Bb,EAAU,GAAAP,MAAAC,KAAqBC,WAC1DM,EAAMX,EAAQY,WAAIF,EAAAA,GAAM,OAAAc,QAAAC,gCAE1BD,QAAAC,QACIJ,EAAUK,QAAQf,IAAIgB,KAAA,WAAA,OAExBrB,EAAMO,IAAIF,GACLL,EAAMQ,IAAIH,GAAea,QAAAC,QAENhC,EAAEmB,WAAA,EAAIF,IAAKiB,KAAA,SAA/BZ,GAIN,OAHIhB,EAAYgB,EAAaJ,IAC3BL,EAAMU,IAAIL,EAAKI,GAEVA,CAAY,EAEtB,4FAd6Ba,CAAA,EAc7BC,SAAAA,EAAAC,GACwB,GAAvBT,EAAUU,QAAQpB,GAAKkB,EAAA,MAAAC,EAAAA,OAAAA,CAAA,GAE3B,CAAC,MAAAE,GAAAR,OAAAA,QAAAS,OAAAD,EAAA,CAAA,EAID,OAFAvB,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.11",
|
|
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,10 +22,14 @@
|
|
|
22
22
|
"test": "vitest"
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"
|
|
25
|
+
"@chriscdn/promise-semaphore": "^3.1.2",
|
|
26
|
+
"quick-lru": "^7.3.0"
|
|
26
27
|
},
|
|
27
28
|
"devDependencies": {
|
|
28
29
|
"microbundle": "^0.15.1",
|
|
29
|
-
"vitest": "^
|
|
30
|
-
}
|
|
30
|
+
"vitest": "^4.0.6"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"lib"
|
|
34
|
+
]
|
|
31
35
|
}
|
|
@@ -1,201 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from "vitest";
|
|
2
|
-
import { Memoize, MemoizeAsync } from "../src/index";
|
|
3
|
-
|
|
4
|
-
let addSyncCount = 0;
|
|
5
|
-
let addAsyncCount = 0;
|
|
6
|
-
|
|
7
|
-
const add = (x: number, y: number) => {
|
|
8
|
-
addSyncCount += 1;
|
|
9
|
-
return x + y;
|
|
10
|
-
};
|
|
11
|
-
|
|
12
|
-
const addAsync = async (x: number, y: number) => {
|
|
13
|
-
addAsyncCount += 1;
|
|
14
|
-
return x + y;
|
|
15
|
-
};
|
|
16
|
-
|
|
17
|
-
const _asyncThrowError = MemoizeAsync(async (x: number, y: number) => {
|
|
18
|
-
addAsyncCount += 1;
|
|
19
|
-
throw new Error("Boom!");
|
|
20
|
-
return x + y;
|
|
21
|
-
});
|
|
22
|
-
|
|
23
|
-
const asyncThrowError = MemoizeAsync(async (x: number, y: number) => {
|
|
24
|
-
try {
|
|
25
|
-
await _asyncThrowError(x, y);
|
|
26
|
-
} catch {
|
|
27
|
-
return -1;
|
|
28
|
-
}
|
|
29
|
-
});
|
|
30
|
-
|
|
31
|
-
describe("Memoization", () => {
|
|
32
|
-
it("sync", async () => {
|
|
33
|
-
const addCached = Memoize(add);
|
|
34
|
-
|
|
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);
|
|
40
|
-
|
|
41
|
-
// different key here
|
|
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
|
-
]);
|
|
58
|
-
|
|
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
|
-
});
|
|
77
|
-
});
|
|
78
|
-
|
|
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
|
-
}
|
|
92
|
-
|
|
93
|
-
it("Test1", () => {
|
|
94
|
-
const obj = new AddClass();
|
|
95
|
-
|
|
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
|
-
});
|
|
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", () => {
|
|
195
|
-
expect(() => errorSync()).toThrowError("errorsync");
|
|
196
|
-
});
|
|
197
|
-
|
|
198
|
-
it("error async", () => {
|
|
199
|
-
expect(errorASync()).rejects.toThrowError("errorasync");
|
|
200
|
-
});
|
|
201
|
-
});
|
package/src/index.ts
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import QuickLRU from "quick-lru";
|
|
2
|
-
|
|
3
|
-
const kDefaultMaxSize = 1000;
|
|
4
|
-
|
|
5
|
-
type Options<T extends any[], Return> = {
|
|
6
|
-
maxSize: number;
|
|
7
|
-
maxAge?: number;
|
|
8
|
-
shouldCache: (returnValue: Return, key: string) => boolean;
|
|
9
|
-
resolver: (...args: T) => string;
|
|
10
|
-
};
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Memoize a synchronous function.
|
|
14
|
-
*/
|
|
15
|
-
const Memoize = <Args extends unknown[], Return>(
|
|
16
|
-
cb: (...args: Args) => Return,
|
|
17
|
-
options: Partial<Options<Args, Return>> = {},
|
|
18
|
-
) => {
|
|
19
|
-
const maxAge: number | undefined = options.maxAge;
|
|
20
|
-
const maxSize = options.maxSize ?? kDefaultMaxSize;
|
|
21
|
-
const shouldCache = options.shouldCache ?? (() => true);
|
|
22
|
-
|
|
23
|
-
const resolver = options.resolver ??
|
|
24
|
-
((...args: Args) => JSON.stringify(args));
|
|
25
|
-
|
|
26
|
-
const cache = new QuickLRU<string, Return>({
|
|
27
|
-
maxAge,
|
|
28
|
-
maxSize,
|
|
29
|
-
});
|
|
30
|
-
|
|
31
|
-
const memoizedFunction = (...args: Args): Return => {
|
|
32
|
-
const key = resolver(...args);
|
|
33
|
-
|
|
34
|
-
if (cache.has(key)) {
|
|
35
|
-
return cache.get(key) as Return;
|
|
36
|
-
} else {
|
|
37
|
-
const returnValue = cb(...args);
|
|
38
|
-
if (shouldCache(returnValue, key)) {
|
|
39
|
-
cache.set(key, returnValue);
|
|
40
|
-
}
|
|
41
|
-
return returnValue;
|
|
42
|
-
}
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
memoizedFunction.cache = cache;
|
|
46
|
-
|
|
47
|
-
return memoizedFunction;
|
|
48
|
-
};
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* @deprecated `Memoize` can be used for asynchronous functions.
|
|
52
|
-
*/
|
|
53
|
-
const MemoizeAsync = Memoize;
|
|
54
|
-
|
|
55
|
-
export { Memoize, MemoizeAsync };
|