Skip to content

Commit ecc89b0

Browse files
committed
Added wrapper function example
1 parent 8c77525 commit ecc89b0

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

README.md

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,14 @@
44

55
[Memoize](https://en.wikipedia.org/wiki/Memoization) sync and async functions (Returning a `Promise`).
66

7-
Used to cache expensive function calls and return the cached result when the same inputs occur again.
7+
Cache expensive function calls and return the cached result when the same inputs occur again.
88

9-
Provides:
9+
This package provides:
1010

1111
- `memoize` Function: Used to memoize any sync or `async` function.
1212
- `memoize` Decorator: **TypeScript** decorator used to memoize class methods and getters.
1313

14-
Can be use to:
14+
Can be used to:
1515

1616
- Cache expensive function calls
1717
- Prevent hitting rate limits on an API when the result can be cached
@@ -99,12 +99,32 @@ instance.result;
9999

100100
| Option | Description | Default |
101101
| ---------------------- | ----------------------------------------------------------------------------------------------------------------- | ----------- |
102-
| `maxAge` | Cached result expiration duration in milliseconds. | `undefined` |
102+
| `maxAge` | Cached results expiration duration in milliseconds (Defaults to no expiration). | `undefined` |
103103
| `cache` | Custom cache instance or a factory function returning a cache instance. | `new Map()` |
104104
| `cacheId` | Custom cache ID function, to be used to determine the ID of the cached result (Defaults to first argument as ID). | `undefined` |
105105
| `cacheRejectedPromise` | Cache the rejected promise when memoizing an `async` function. | `false` |
106106
| `cacheFromContext` | Function returning a custom cache instance that has access to the original function's context `this`. | `undefined` |
107107

108+
To customize these defaults, you can create a wrapper function:
109+
110+
```js
111+
import { memoize as memoizeFn } from 'memoize-utils';
112+
113+
export function memoize(fn, options) {
114+
const defaults = {
115+
maxAge: 60 * 60 * 1000, // Cache expires in 1 hour
116+
cache: new LRUCache(), // Use a custom cache instance
117+
cacheId: (obj) => obj.id, // Use a specific ID assuming your first arg is an object
118+
// ...
119+
};
120+
121+
return memoizeFn(fn, { defaults, ...options });
122+
}
123+
124+
// Use the new wrapper function
125+
const memoized = memoize(expensiveFunction);
126+
```
127+
108128
## Cache Expiration
109129

110130
Cached results are stored with a timestamp, the `maxAge` option can be passed when creating the memoized function to set the expiration duration of the cache.

0 commit comments

Comments
 (0)