|
4 | 4 |
|
5 | 5 | [Memoize](https://en.wikipedia.org/wiki/Memoization) sync and async functions (Returning a `Promise`).
|
6 | 6 |
|
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. |
8 | 8 |
|
9 |
| -Provides: |
| 9 | +This package provides: |
10 | 10 |
|
11 | 11 | - `memoize` Function: Used to memoize any sync or `async` function.
|
12 | 12 | - `memoize` Decorator: **TypeScript** decorator used to memoize class methods and getters.
|
13 | 13 |
|
14 |
| -Can be use to: |
| 14 | +Can be used to: |
15 | 15 |
|
16 | 16 | - Cache expensive function calls
|
17 | 17 | - Prevent hitting rate limits on an API when the result can be cached
|
@@ -99,12 +99,32 @@ instance.result;
|
99 | 99 |
|
100 | 100 | | Option | Description | Default |
|
101 | 101 | | ---------------------- | ----------------------------------------------------------------------------------------------------------------- | ----------- |
|
102 |
| -| `maxAge` | Cached result expiration duration in milliseconds. | `undefined` | |
| 102 | +| `maxAge` | Cached results expiration duration in milliseconds (Defaults to no expiration). | `undefined` | |
103 | 103 | | `cache` | Custom cache instance or a factory function returning a cache instance. | `new Map()` |
|
104 | 104 | | `cacheId` | Custom cache ID function, to be used to determine the ID of the cached result (Defaults to first argument as ID). | `undefined` |
|
105 | 105 | | `cacheRejectedPromise` | Cache the rejected promise when memoizing an `async` function. | `false` |
|
106 | 106 | | `cacheFromContext` | Function returning a custom cache instance that has access to the original function's context `this`. | `undefined` |
|
107 | 107 |
|
| 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 | + |
108 | 128 | ## Cache Expiration
|
109 | 129 |
|
110 | 130 | 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