Skip to content

Commit

Permalink
Document the cacheId helper functions
Browse files Browse the repository at this point in the history
  • Loading branch information
mdawar committed Jun 28, 2022
1 parent 8de9d93 commit 4425527
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
43 changes: 42 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ Required `cache` object methods:

## Cache ID

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

```js
const memoized = memoize(expensiveFunction);
Expand Down Expand Up @@ -222,6 +222,47 @@ memoized(/(.*)/); // Cached
memoized(/(.*)/); // Cached
```

### Cache ID Helpers

The module `memoize-utils/helpers` provides some commonly used `cacheId` functions:

- `all`: Get an ID from all the arguments casted to a string and then joined together.
- `json`: Get a JSON string ID from the arguments (`JSON.stringify(args)`).
- `anyOrder`: Get the same ID from a set of arguments passed in any order.

Usage:

```js
import { all, json, anyOrder } from 'memoize-utils/helpers';

// Use all the arguments as an ID
// Note: does not work with objects (Arguments are casted to strings)
// but it works with `RegExp` objects
memoize(fn, { cacheId: all });

// Use all the arguments as an ID including objects
// Note: does not work with `RegExp` objects
memoize(fn, { cacheId: json });

// Use all the arguments as an ID but in any order
// Note: does not work with objects (Arguments are casted to strings)
memoize(fn, { cacheId: anyOrder });
```

You can create your own `memoize` wrapper function using a custom cache ID:

```js
import { memoize } from 'memoize-utils';
import { anyOrder } from 'memoize-utils/helpers';

export function memoizeAnyOrder(fn, options) {
return memoize(fn, { cacheId: anyOrder, ...options });
}

// Memoize functions using all of the arguments as a cache ID in any order
const memoized = memoizeAnyOrder(fn);
```

## Rejected Promises

By default rejected promises are not cached, this is done to have the same functionality for synchronous functions when throwing errors.
Expand Down
2 changes: 1 addition & 1 deletion src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function json(...args: readonly any[]): string {
}

/**
* Get the same ID from a set of arguments no matter the order they're passed in.
* Get the same ID from a set of arguments passed in any order.
*
* The passed arguments are sorted and then casted to a string and then joined together.
*
Expand Down

0 comments on commit 4425527

Please sign in to comment.