@checkdigit/memoize 5.0.0-PR.19-b872 → 5.0.0-PR.19-ddb5

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 CHANGED
@@ -43,6 +43,44 @@ properties.
43
43
  `Uint8Array` and `Buffer` are keyed by their bytes and type. The corresponding JSON values have
44
44
  separate cache entries.
45
45
 
46
+ ## Cache options
47
+
48
+ Pass `cacheKey` to compute a key from the full argument list. A custom key skips structural serialization and
49
+ can use any value your cache accepts. Pass `cache` to use a synchronous store with `get`, `set`, and `delete`
50
+ methods. The store holds the original promises and returns `undefined` on a miss.
51
+
52
+ ```ts
53
+ const cache = new Map<number, Promise<string>>();
54
+ const readName = memoize(
55
+ async (user: { id: number; name: string }) => user.name,
56
+ {
57
+ cacheKey: ([user]) => user.id,
58
+ cache,
59
+ },
60
+ );
61
+
62
+ await readName({ id: 1, name: 'Alice' });
63
+ cache.delete(1);
64
+ ```
65
+
66
+ Supply a dedicated cache or namespace keys when sharing one between functions. Evicting a pending promise
67
+ allows the next call for that key to start new work. The memoizer removes rejected promises it inserted.
68
+
69
+ ### Bounded cache with `lru-cache`
70
+
71
+ Install `lru-cache` alongside `@checkdigit/memoize`. Given an async `getUser(id)` function that returns a `User`:
72
+
73
+ ```ts
74
+ import memoize from '@checkdigit/memoize';
75
+ import { LRUCache } from 'lru-cache';
76
+
77
+ const readUser = memoize(getUser, {
78
+ cacheKey: ([id]) => id,
79
+ // cache keeps up to 500 entries. 60-second TTL starts when the promise is inserted.
80
+ cache: new LRUCache<string, Promise<User>>({ max: 500, ttl: 60_000 }),
81
+ });
82
+ ```
83
+
46
84
  ## License
47
85
 
48
86
  MIT
@@ -1,6 +1,8 @@
1
1
  // src/index.ts
2
- import { default as default2 } from "./memoize.mjs";
2
+ import {
3
+ default as default2
4
+ } from "./memoize.mjs";
3
5
  export {
4
6
  default2 as default
5
7
  };
6
- //# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vc3JjL2luZGV4LnRzIl0sCiAgIm1hcHBpbmdzIjogIjtBQVFBLFNBQWlELFdBQUFBLGdCQUFlOyIsCiAgIm5hbWVzIjogWyJkZWZhdWx0Il0KfQo=
8
+ //# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vc3JjL2luZGV4LnRzIl0sCiAgIm1hcHBpbmdzIjogIjtBQVFBO0FBQUEsRUFLRSxXQUFBQTtBQUFBLE9BQ0s7IiwKICAibmFtZXMiOiBbImRlZmF1bHQiXQp9Cg==
@@ -1,100 +1,118 @@
1
1
  // src/memoize.ts
2
2
  import builtInKey from "./built-in-key.mjs";
3
- var memoize_default = (memoizableFunction) => {
4
- const cache = /* @__PURE__ */ new Map();
3
+ function createStructuralKey() {
5
4
  const symbols = /* @__PURE__ */ new Map();
6
5
  const functionKeys = /* @__PURE__ */ new WeakMap();
7
6
  const seed = crypto.getRandomValues(new Uint32Array(4)).join("-");
8
7
  let referenceId = 0;
9
- return (...argumentList) => {
8
+ return (argumentList) => {
10
9
  const converted = JSON.stringify(
11
10
  argumentList,
12
11
  // eslint-disable-next-line sonarjs/function-return-type
13
- function(key, value2) {
14
- if (typeof value2 === "string" || typeof value2 === "object") {
12
+ function(key, value) {
13
+ if (typeof value === "string" || typeof value === "object") {
15
14
  const original = Object.getOwnPropertyDescriptor(
16
15
  this,
17
16
  key
18
17
  )?.value;
19
18
  if (typeof original === "object" && original !== null) {
20
- const builtInKeyResult = builtInKey(original, value2);
19
+ const builtInKeyResult = builtInKey(original, value);
21
20
  if (builtInKeyResult !== void 0) {
22
21
  return `${seed}:${builtInKeyResult}`;
23
22
  }
24
23
  }
25
24
  }
26
- switch (typeof value2) {
25
+ switch (typeof value) {
27
26
  case "bigint": {
28
- return `${seed}:${value2}n`;
27
+ return `${seed}:${value}n`;
29
28
  }
30
29
  case "undefined": {
31
30
  return `${seed}:undefined'`;
32
31
  }
33
32
  case "symbol": {
34
- let symbolUniqueStringValue = symbols.get(value2);
33
+ let symbolUniqueStringValue = symbols.get(value);
35
34
  if (symbolUniqueStringValue === void 0) {
36
35
  symbolUniqueStringValue = `${seed}:symbol:${++referenceId}`;
37
- symbols.set(value2, symbolUniqueStringValue);
36
+ symbols.set(value, symbolUniqueStringValue);
38
37
  }
39
38
  return symbolUniqueStringValue;
40
39
  }
41
40
  case "function": {
42
- let functionKey = functionKeys.get(value2);
41
+ let functionKey = functionKeys.get(value);
43
42
  if (functionKey === void 0) {
44
43
  functionKey = `${seed}:function:${++referenceId}`;
45
- functionKeys.set(value2, functionKey);
44
+ functionKeys.set(value, functionKey);
46
45
  }
47
46
  return functionKey;
48
47
  }
49
48
  case "object": {
50
- if (value2 === null) {
49
+ if (value === null) {
51
50
  return null;
52
51
  }
53
- if (Array.isArray(value2)) {
54
- return value2;
52
+ if (Array.isArray(value)) {
53
+ return value;
55
54
  }
56
- const prototype = Reflect.getPrototypeOf(value2);
57
- if (prototype !== null && Reflect.get(prototype, "constructor", value2) === Object) {
58
- return value2;
55
+ const prototype = Reflect.getPrototypeOf(value);
56
+ if (prototype !== null && Reflect.get(prototype, "constructor", value) === Object) {
57
+ return value;
59
58
  }
60
59
  throw new TypeError(`Object argument cannot be memoized`);
61
60
  }
62
61
  case "number": {
63
- if (Object.is(value2, -0)) {
62
+ if (Object.is(value, -0)) {
64
63
  return `${seed}:number:-0`;
65
64
  }
66
- return Number.isFinite(value2) ? value2 : `${seed}:number:${value2}`;
65
+ return Number.isFinite(value) ? value : `${seed}:number:${value}`;
67
66
  }
68
67
  case "boolean":
69
68
  case "string": {
70
- return value2;
69
+ return value;
71
70
  }
72
71
  }
73
72
  }
74
73
  );
75
- const cacheKey = JSON.stringify(
76
- JSON.parse(converted),
77
- (_, value2) => {
78
- if (value2 === null || typeof value2 !== "object" || Array.isArray(value2)) {
79
- return value2;
80
- }
81
- const record = value2;
82
- const keys = Object.keys(record).toSorted();
83
- return Object.fromEntries(keys.map((key) => [key, record[key]]));
74
+ return JSON.stringify(JSON.parse(converted), (_, value) => {
75
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
76
+ return value;
84
77
  }
85
- );
86
- let value = cache.get(cacheKey);
87
- if (value === void 0) {
88
- value = memoizableFunction(...argumentList);
89
- cache.set(cacheKey, value);
90
- value.catch(() => {
91
- cache.delete(cacheKey);
92
- });
78
+ const record = value;
79
+ const keys = Object.keys(record).toSorted();
80
+ return Object.fromEntries(keys.map((key) => [key, record[key]]));
81
+ });
82
+ };
83
+ }
84
+ function memoizeWithKey(memoizableFunction, keyFor, cache = /* @__PURE__ */ new Map()) {
85
+ return (...argumentList) => {
86
+ const key = keyFor(argumentList);
87
+ const cached = cache.get(key);
88
+ if (cached !== void 0) {
89
+ return cached;
93
90
  }
94
- return value;
91
+ const promise = memoizableFunction(...argumentList);
92
+ promise.catch(() => {
93
+ try {
94
+ if (cache.get(key) === promise) {
95
+ cache.delete(key);
96
+ }
97
+ } catch {
98
+ }
99
+ });
100
+ cache.set(key, promise);
101
+ return promise;
95
102
  };
96
- };
103
+ }
104
+ function memoize(memoizableFunction, options = {}) {
105
+ const { cacheKey, cache } = options;
106
+ if (cacheKey === void 0) {
107
+ return memoizeWithKey(memoizableFunction, createStructuralKey(), cache);
108
+ }
109
+ return memoizeWithKey(
110
+ memoizableFunction,
111
+ (argumentList) => cacheKey([...argumentList]),
112
+ cache
113
+ );
114
+ }
97
115
  export {
98
- memoize_default as default
116
+ memoize as default
99
117
  };
100
- //# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vc3JjL21lbW9pemUudHMiXSwKICAibWFwcGluZ3MiOiAiO0FBUUEsT0FBTyxnQkFBZ0I7QUFpQnZCLElBQU8sa0JBQVEsQ0FDYix1QkFDMEM7QUFDMUMsUUFBTSxRQUFRLG9CQUFJLElBQTZCO0FBQy9DLFFBQU0sVUFBVSxvQkFBSSxJQUFvQjt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xTQUFTLGVBQ1Asb0JBQ0EsUUFDQSxRQUFtQyxvQkFBSSxJQUEwQixHQUMxQjtBQUN2QyxTQUFPLElBQUksaUJBQWlCO0FBQzFCLFVBQU0sTUFBTSxPQUFPLFlBQVk7QUFDL0IsVUFBTSxTQUFTLE1BQU0sSUFBSSxHQUFHO0FBQzVCLFFBQUksV0FBVyxRQUFXO0FBQ3hCLGFBQU87QUFBQSxJQUNUO0FBRUEsVUFBTSxVQUFVLG1CQUFtQixHQUFHLFlBQVk7QUFFbEQsWUFBUSxNQUFNLE1BQU07QUFDbEIsVUFBSTtBQUVGLFlBQUksTUFBTSxJQUFJLEdBQUcsTUFBTSxTQUFTO0FBQzlCLGdCQUFNLE9BQU8sR0FBRztBQUFBLFFBQ2xCO0FBQUEsTUFDRixRQUFRO0FBQUEsTUFFUjtBQUFBLElBQ0YsQ0FBQztBQUNELFVBQU0sSUFBSSxLQUFLLE9BQU87QUFDdEIsV0FBTztBQUFBLEVBQ1Q7QUFDRjtBQWdCZSxTQUFSLFFBQ0wsb0JBQ0EsVUFBa0QsQ0FBQyxHQUNaO0FBQ3ZDLFFBQU0sRUFBRSxVQUFVLE1BQU0sSUFBSTtBQUM1QixNQUFJLGFBQWEsUUFBVztBQUMxQixXQUFPLGVBQWUsb0JBQW9CLG9CQUFvQixHQUFHLEtBQUs7QUFBQSxFQUN4RTtBQUVBLFNBQU87QUFBQSxJQUNMO0FBQUEsSUFDQSxDQUFDLGlCQUFpQixTQUFTLENBQUMsR0FBRyxZQUFZLENBQUM7QUFBQSxJQUM1QztBQUFBLEVBQ0Y7QUFDRjsiLAogICJuYW1lcyI6IFtdCn0K
@@ -1 +1 @@
1
- export { type Argument, type MemoizableFunction, default } from './memoize.ts';
1
+ export { type Argument, type MemoizableFunction, type MemoizeCache, type MemoizeOptions, default, } from './memoize.ts';
@@ -1,11 +1,25 @@
1
1
  export type Argument = string | symbol | bigint | number | boolean | null | undefined | object;
2
2
  export type MemoizableFunction<Arguments extends Argument[], Return> = (...argumentList: Arguments) => Promise<Return>;
3
+ export interface MemoizeCache<Key, Return> {
4
+ get: (key: Key) => Promise<Return> | undefined;
5
+ set: (key: Key, value: Promise<Return>) => void;
6
+ delete: (key: Key) => void;
7
+ }
8
+ interface StructuralCacheOptions<Return> {
9
+ cacheKey?: undefined;
10
+ cache?: MemoizeCache<string, NoInfer<Return>>;
11
+ }
12
+ interface CustomKeyOptions<Arguments extends Argument[], Return, Key> {
13
+ cacheKey: (argumentList: Readonly<Arguments>) => Key;
14
+ cache?: MemoizeCache<Key, NoInfer<Return>>;
15
+ }
16
+ export type MemoizeOptions<Arguments extends Argument[], Return, Key = string> = StructuralCacheOptions<Return> | CustomKeyOptions<Arguments, Return, Key>;
3
17
  /**
4
- * Memoize an async function. The promise is cached, not the value. This guarantees the underlying function is
5
- * called at most once for a given set of arguments, unless the promise is rejected.
6
- * If the promise is rejected, it will be removed from the memoize cache. This allows the function to be retried.
18
+ * Memoizes an async function by caching its original promise until eviction or rejection.
7
19
  *
8
- * @param memoizableFunction async function to memoize
20
+ * @param memoizableFunction Async function to memoize.
21
+ * @param options Optional key function and synchronous cache.
9
22
  */
10
- declare const _default: <Arguments extends Argument[], Return>(memoizableFunction: MemoizableFunction<Arguments, Return>) => MemoizableFunction<Arguments, Return>;
11
- export default _default;
23
+ export default function memoize<Arguments extends Argument[], Return>(memoizableFunction: MemoizableFunction<Arguments, Return>, options?: StructuralCacheOptions<Return>): MemoizableFunction<Arguments, Return>;
24
+ export default function memoize<Arguments extends Argument[], Return, Key>(memoizableFunction: MemoizableFunction<Arguments, Return>, options: MemoizeOptions<Arguments, Return, Key>): MemoizableFunction<Arguments, Return>;
25
+ export {};
package/package.json CHANGED
@@ -1 +1 @@
1
- {"name":"@checkdigit/memoize","version":"5.0.0-PR.19-b872","description":"Memoizing async functions with cache eviction on reject","homepage":"https://github.com/checkdigit/memoize#readme","bugs":{"url":"https://github.com/checkdigit/memoize/issues"},"repository":{"type":"git","url":"git+https://github.com/checkdigit/memoize.git"},"license":"MIT","author":"Check Digit, LLC","sideEffects":false,"type":"module","exports":{".":{"types":"./dist-types/index.d.ts","import":"./dist-mjs/index.mjs","default":"./dist-mjs/index.mjs"}},"files":["src","dist-types","dist-mjs","!src/**/*.test.ts","!src/**/*.spec.ts","!dist-types/**/*.test.d.ts","!dist-types/**/*.spec.d.ts","!dist-mjs/**/*.test.mjs","!dist-mjs/**/*.spec.mjs","SECURITY.md"],"scripts":{"build:dist-mjs":"node -e \"require('node:fs').rmSync('dist-mjs', { recursive: true, force: true })\" && npx builder --type=module --sourceMap --outDir=dist-mjs && node dist-mjs/index.mjs","build:dist-types":"node -e \"require('node:fs').rmSync('dist-types', { recursive: true, force: true })\" && npx builder --type=types --outDir=dist-types","ci:compile":"tsc --noEmit","ci:coverage":"node -e \"const fs = require('node:fs'); fs.rmSync('coverage', { recursive: true, force: true }); fs.mkdirSync('coverage')\" && node --test-timeout 600000 --experimental-test-coverage --test-coverage-exclude=\"**/*.spec.ts\" --test-coverage-exclude=\"**/*.test.ts\" --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test \"src/**/*.spec.ts\"","ci:lint":"npm run lint","ci:style":"npm run prettier","ci:test":"node --pending-deprecation --throw-deprecation --test-timeout 600000 --test \"src/**/*.spec.ts\"","coverage":"node --test-timeout 600000 --experimental-test-coverage --test-coverage-exclude=\"**/*.spec.ts\" --test-coverage-exclude=\"**/*.test.ts\" --test \"src/**/*.spec.ts\"","lint":"eslint --max-warnings 0 .","lint:fix":"eslint . --fix","prepublishOnly":"npm run build:dist-types && npm run build:dist-mjs","prettier":"prettier . --check","prettier:fix":"prettier . --write","test":"npm run ci:compile && npm run ci:test && npm run ci:lint && npm run ci:style"},"prettier":"@checkdigit/prettier-config","devDependencies":{"@checkdigit/eslint-config":"^12.3.0","@checkdigit/prettier-config":"^8.4.0","@checkdigit/typescript-config":"^10.2.2"},"engines":{"node":">=26.13.0"}}
1
+ {"name":"@checkdigit/memoize","version":"5.0.0-PR.19-ddb5","description":"Memoizing async functions with cache eviction on reject","homepage":"https://github.com/checkdigit/memoize#readme","bugs":{"url":"https://github.com/checkdigit/memoize/issues"},"repository":{"type":"git","url":"git+https://github.com/checkdigit/memoize.git"},"license":"MIT","author":"Check Digit, LLC","sideEffects":false,"type":"module","exports":{".":{"types":"./dist-types/index.d.ts","import":"./dist-mjs/index.mjs","default":"./dist-mjs/index.mjs"}},"files":["src","dist-types","dist-mjs","!src/**/*.test.ts","!src/**/*.spec.ts","!dist-types/**/*.test.d.ts","!dist-types/**/*.spec.d.ts","!dist-mjs/**/*.test.mjs","!dist-mjs/**/*.spec.mjs","SECURITY.md"],"scripts":{"build:dist-mjs":"node -e \"require('node:fs').rmSync('dist-mjs', { recursive: true, force: true })\" && npx builder --type=module --sourceMap --outDir=dist-mjs && node dist-mjs/index.mjs","build:dist-types":"node -e \"require('node:fs').rmSync('dist-types', { recursive: true, force: true })\" && npx builder --type=types --outDir=dist-types","ci:compile":"tsc --noEmit","ci:coverage":"node -e \"const fs = require('node:fs'); fs.rmSync('coverage', { recursive: true, force: true }); fs.mkdirSync('coverage')\" && node --test-timeout 600000 --experimental-test-coverage --test-coverage-exclude=\"**/*.spec.ts\" --test-coverage-exclude=\"**/*.test.ts\" --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test \"src/**/*.spec.ts\"","ci:lint":"npm run lint","ci:style":"npm run prettier","ci:test":"node --pending-deprecation --throw-deprecation --test-timeout 600000 --test \"src/**/*.spec.ts\"","coverage":"node --test-timeout 600000 --experimental-test-coverage --test-coverage-exclude=\"**/*.spec.ts\" --test-coverage-exclude=\"**/*.test.ts\" --test \"src/**/*.spec.ts\"","lint":"eslint --max-warnings 0 .","lint:fix":"eslint . --fix","prepublishOnly":"npm run build:dist-types && npm run build:dist-mjs","prettier":"prettier . --check","prettier:fix":"prettier . --write","test":"npm run ci:compile && npm run ci:test && npm run ci:lint && npm run ci:style"},"prettier":"@checkdigit/prettier-config","devDependencies":{"@checkdigit/eslint-config":"^12.3.0","@checkdigit/prettier-config":"^8.4.0","@checkdigit/typescript-config":"^10.2.2","lru-cache":"^11.5.3"},"engines":{"node":">=26.13.0"}}
package/src/index.ts CHANGED
@@ -6,4 +6,10 @@
6
6
  * This code is licensed under the MIT license (see LICENSE.txt for details).
7
7
  */
8
8
 
9
- export { type Argument, type MemoizableFunction, default } from './memoize.ts';
9
+ export {
10
+ type Argument,
11
+ type MemoizableFunction,
12
+ type MemoizeCache,
13
+ type MemoizeOptions,
14
+ default,
15
+ } from './memoize.ts';
package/src/memoize.ts CHANGED
@@ -16,17 +16,26 @@ export type MemoizableFunction<Arguments extends Argument[], Return> = (
16
16
  ...argumentList: Arguments
17
17
  ) => Promise<Return>;
18
18
 
19
- /**
20
- * Memoize an async function. The promise is cached, not the value. This guarantees the underlying function is
21
- * called at most once for a given set of arguments, unless the promise is rejected.
22
- * If the promise is rejected, it will be removed from the memoize cache. This allows the function to be retried.
23
- *
24
- * @param memoizableFunction async function to memoize
25
- */
26
- export default <Arguments extends Argument[], Return>(
27
- memoizableFunction: MemoizableFunction<Arguments, Return>,
28
- ): MemoizableFunction<Arguments, Return> => {
29
- const cache = new Map<string, Promise<Return>>();
19
+ export interface MemoizeCache<Key, Return> {
20
+ get: (key: Key) => Promise<Return> | undefined;
21
+ set: (key: Key, value: Promise<Return>) => void;
22
+ delete: (key: Key) => void;
23
+ }
24
+
25
+ interface StructuralCacheOptions<Return> {
26
+ cacheKey?: undefined;
27
+ cache?: MemoizeCache<string, NoInfer<Return>>;
28
+ }
29
+
30
+ interface CustomKeyOptions<Arguments extends Argument[], Return, Key> {
31
+ cacheKey: (argumentList: Readonly<Arguments>) => Key;
32
+ cache?: MemoizeCache<Key, NoInfer<Return>>;
33
+ }
34
+
35
+ export type MemoizeOptions<Arguments extends Argument[], Return, Key = string> =
36
+ StructuralCacheOptions<Return> | CustomKeyOptions<Arguments, Return, Key>;
37
+
38
+ function createStructuralKey(): (argumentList: readonly Argument[]) => string {
30
39
  const symbols = new Map<symbol, string>();
31
40
  const functionKeys = new WeakMap<object, string>();
32
41
 
@@ -34,7 +43,7 @@ export default <Arguments extends Argument[], Return>(
34
43
  const seed = crypto.getRandomValues(new Uint32Array(4)).join('-');
35
44
  let referenceId = 0;
36
45
 
37
- return (...argumentList) => {
46
+ return (argumentList) => {
38
47
  const converted = JSON.stringify(
39
48
  argumentList,
40
49
  // eslint-disable-next-line sonarjs/function-return-type
@@ -116,33 +125,73 @@ export default <Arguments extends Argument[], Return>(
116
125
  );
117
126
 
118
127
  // sort each object's own keys while preserving array order.
119
- const cacheKey = JSON.stringify(
120
- JSON.parse(converted),
121
- (_, value: unknown) => {
122
- if (
123
- value === null ||
124
- typeof value !== 'object' ||
125
- Array.isArray(value)
126
- ) {
127
- return value;
128
- }
129
- const record = value as Record<string, unknown>;
130
- // eslint-disable-next-line sonarjs/no-alphabetical-sort, unicorn/require-array-sort-compare -- use default UTF-16 code-unit ordering
131
- const keys = Object.keys(record).toSorted();
132
- return Object.fromEntries(keys.map((key) => [key, record[key]]));
133
- },
134
- );
128
+ return JSON.stringify(JSON.parse(converted), (_, value: unknown) => {
129
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
130
+ return value;
131
+ }
132
+ const record = value as Record<string, unknown>;
133
+ // eslint-disable-next-line sonarjs/no-alphabetical-sort, unicorn/require-array-sort-compare -- use default UTF-16 code-unit ordering
134
+ const keys = Object.keys(record).toSorted();
135
+ return Object.fromEntries(keys.map((key) => [key, record[key]]));
136
+ });
137
+ };
138
+ }
135
139
 
136
- let value = cache.get(cacheKey);
137
- if (value === undefined) {
138
- value = memoizableFunction(...argumentList);
139
- cache.set(cacheKey, value);
140
- // eslint-disable-next-line @checkdigit/no-promise-instance-method, unicorn/prefer-await -- preserve the cached promise's identity
141
- value.catch(() => {
142
- // on a reject, evict key from cache
143
- cache.delete(cacheKey);
144
- });
140
+ function memoizeWithKey<Arguments extends Argument[], Return, Key>(
141
+ memoizableFunction: MemoizableFunction<Arguments, Return>,
142
+ keyFor: (arguments_: Arguments) => Key,
143
+ cache: MemoizeCache<Key, Return> = new Map<Key, Promise<Return>>(),
144
+ ): MemoizableFunction<Arguments, Return> {
145
+ return (...argumentList) => {
146
+ const key = keyFor(argumentList);
147
+ const cached = cache.get(key);
148
+ if (cached !== undefined) {
149
+ return cached;
145
150
  }
146
- return value;
151
+
152
+ const promise = memoizableFunction(...argumentList);
153
+ // eslint-disable-next-line @checkdigit/no-promise-instance-method, unicorn/prefer-await -- preserve the cached promise's identity
154
+ promise.catch(() => {
155
+ try {
156
+ // custom cache may have evicted this promise and stored a newer one.
157
+ if (cache.get(key) === promise) {
158
+ cache.delete(key);
159
+ }
160
+ } catch {
161
+ // cache error during cleanup must not create a second rejection.
162
+ }
163
+ });
164
+ cache.set(key, promise);
165
+ return promise;
147
166
  };
148
- };
167
+ }
168
+
169
+ /**
170
+ * Memoizes an async function by caching its original promise until eviction or rejection.
171
+ *
172
+ * @param memoizableFunction Async function to memoize.
173
+ * @param options Optional key function and synchronous cache.
174
+ */
175
+ export default function memoize<Arguments extends Argument[], Return>(
176
+ memoizableFunction: MemoizableFunction<Arguments, Return>,
177
+ options?: StructuralCacheOptions<Return>,
178
+ ): MemoizableFunction<Arguments, Return>;
179
+ export default function memoize<Arguments extends Argument[], Return, Key>(
180
+ memoizableFunction: MemoizableFunction<Arguments, Return>,
181
+ options: MemoizeOptions<Arguments, Return, Key>,
182
+ ): MemoizableFunction<Arguments, Return>;
183
+ export default function memoize<Arguments extends Argument[], Return, Key>(
184
+ memoizableFunction: MemoizableFunction<Arguments, Return>,
185
+ options: MemoizeOptions<Arguments, Return, Key> = {},
186
+ ): MemoizableFunction<Arguments, Return> {
187
+ const { cacheKey, cache } = options;
188
+ if (cacheKey === undefined) {
189
+ return memoizeWithKey(memoizableFunction, createStructuralKey(), cache);
190
+ }
191
+
192
+ return memoizeWithKey(
193
+ memoizableFunction,
194
+ (argumentList) => cacheKey([...argumentList]),
195
+ cache,
196
+ );
197
+ }