Skip to content

Commit 4425527

Browse files
committed
Document the cacheId helper functions
1 parent 8de9d93 commit 4425527

File tree

2 files changed

+43
-2
lines changed

2 files changed

+43
-2
lines changed

README.md

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ Required `cache` object methods:
158158

159159
## Cache ID
160160

161-
By default the first argument of the memoized function is used as the cache ID to store the result.
161+
By default the **first argument** of the memoized function is used as the cache ID to store the result.
162162

163163
```js
164164
const memoized = memoize(expensiveFunction);
@@ -222,6 +222,47 @@ memoized(/(.*)/); // Cached
222222
memoized(/(.*)/); // Cached
223223
```
224224

225+
### Cache ID Helpers
226+
227+
The module `memoize-utils/helpers` provides some commonly used `cacheId` functions:
228+
229+
- `all`: Get an ID from all the arguments casted to a string and then joined together.
230+
- `json`: Get a JSON string ID from the arguments (`JSON.stringify(args)`).
231+
- `anyOrder`: Get the same ID from a set of arguments passed in any order.
232+
233+
Usage:
234+
235+
```js
236+
import { all, json, anyOrder } from 'memoize-utils/helpers';
237+
238+
// Use all the arguments as an ID
239+
// Note: does not work with objects (Arguments are casted to strings)
240+
// but it works with `RegExp` objects
241+
memoize(fn, { cacheId: all });
242+
243+
// Use all the arguments as an ID including objects
244+
// Note: does not work with `RegExp` objects
245+
memoize(fn, { cacheId: json });
246+
247+
// Use all the arguments as an ID but in any order
248+
// Note: does not work with objects (Arguments are casted to strings)
249+
memoize(fn, { cacheId: anyOrder });
250+
```
251+
252+
You can create your own `memoize` wrapper function using a custom cache ID:
253+
254+
```js
255+
import { memoize } from 'memoize-utils';
256+
import { anyOrder } from 'memoize-utils/helpers';
257+
258+
export function memoizeAnyOrder(fn, options) {
259+
return memoize(fn, { cacheId: anyOrder, ...options });
260+
}
261+
262+
// Memoize functions using all of the arguments as a cache ID in any order
263+
const memoized = memoizeAnyOrder(fn);
264+
```
265+
225266
## Rejected Promises
226267

227268
By default rejected promises are not cached, this is done to have the same functionality for synchronous functions when throwing errors.

src/helpers.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ export function json(...args: readonly any[]): string {
2323
}
2424

2525
/**
26-
* Get the same ID from a set of arguments no matter the order they're passed in.
26+
* Get the same ID from a set of arguments passed in any order.
2727
*
2828
* The passed arguments are sorted and then casted to a string and then joined together.
2929
*

0 commit comments

Comments
 (0)