0
# Lodash Memoize
1
2
Lodash Memoize is a utility function that creates memoized versions of functions to cache expensive computation results for performance optimization. It provides configurable caching with support for custom key resolution and cache implementations.
3
4
## Package Information
5
6
- **Package Name**: lodash.memoize
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install lodash.memoize`
10
11
## Core Imports
12
13
```javascript
14
const memoize = require('lodash.memoize');
15
```
16
17
For ES modules:
18
19
```javascript
20
import memoize from 'lodash.memoize';
21
```
22
23
## Basic Usage
24
25
```javascript
26
const memoize = require('lodash.memoize');
27
28
// Memoize an expensive function
29
const expensiveFunction = (n) => {
30
console.log('Computing...');
31
return n * n;
32
};
33
34
const memoizedFunction = memoize(expensiveFunction);
35
36
// First call - computes and caches
37
memoizedFunction(5); // Logs "Computing...", returns 25
38
39
// Second call - returns cached result
40
memoizedFunction(5); // Returns 25 (no log)
41
42
// Access the cache directly
43
console.log(memoizedFunction.cache.has(5)); // true
44
console.log(memoizedFunction.cache.get(5)); // 25
45
```
46
47
## Capabilities
48
49
### Memoization Function
50
51
Creates a function that memoizes the result of the provided function.
52
53
```javascript { .api }
54
/**
55
* Creates a function that memoizes the result of func
56
* @param {Function} func - The function to have its output memoized
57
* @param {Function} [resolver] - The function to resolve the cache key
58
* @returns {Function} Returns the new memoizing function
59
* @throws {TypeError} If func is not a function or resolver is provided but not a function
60
*/
61
function memoize(func, resolver);
62
```
63
64
**Parameters:**
65
- `func` (Function): The function to memoize
66
- `resolver` (Function, optional): Custom function to determine cache keys from arguments. If not provided, uses the first argument as the cache key.
67
68
**Returns:**
69
- Function: A memoized version of the input function with attached cache
70
71
**Caching Behavior:**
72
- By default, only the first argument is used as the cache key
73
- Multiple arguments require a custom resolver function
74
- Cache keys are converted to strings internally
75
76
**Usage Examples:**
77
78
```javascript
79
// Basic memoization
80
const square = memoize(n => n * n);
81
82
// Custom cache key resolver
83
const multiArgFunction = (a, b, c) => a + b + c;
84
const memoizedMulti = memoize(multiArgFunction, (a, b, c) => `${a}-${b}-${c}`);
85
86
// Object method memoization
87
const obj = {
88
getValue: memoize(function(key) {
89
return this.data[key];
90
})
91
};
92
```
93
94
### Cache Configuration
95
96
The Cache constructor used by memoize functions, replaceable with custom implementations.
97
98
```javascript { .api }
99
/**
100
* Cache constructor for memoized functions
101
* Default implementation: MapCache
102
* Can be replaced with custom cache implementations like WeakMap
103
*/
104
memoize.Cache;
105
```
106
107
**Usage Examples:**
108
109
```javascript
110
// Replace default cache with WeakMap for object keys
111
memoize.Cache = WeakMap;
112
113
const objectProcessor = memoize(obj => obj.processed = true);
114
115
// Reset to default cache
116
memoize.Cache = memoize.Cache.constructor;
117
```
118
119
### Cache Interface
120
121
The cache attached to each memoized function supports the following methods:
122
123
```javascript { .api }
124
/**
125
* Cache instance attached to memoized functions
126
* Implements Map-like interface
127
*/
128
interface Cache {
129
/**
130
* Gets the cached value for key
131
* @param {*} key - The key of the value to get (converted to string internally)
132
* @returns {*} Returns the cached value
133
*/
134
get(key);
135
136
/**
137
* Sets value to key of the cache
138
* @param {*} key - The key of the value to cache (converted to string internally)
139
* @param {*} value - The value to cache
140
* @returns {Cache} Returns the cache instance
141
*/
142
set(key, value);
143
144
/**
145
* Checks if a cached value for key exists
146
* @param {*} key - The key of the entry to check (converted to string internally)
147
* @returns {boolean} Returns true if an entry for key exists, else false
148
*/
149
has(key);
150
151
/**
152
* Removes key and its value from the cache
153
* @param {*} key - The key of the value to remove (converted to string internally)
154
* @returns {boolean} Returns true if the entry was removed successfully, else false
155
*/
156
delete(key);
157
}
158
```
159
160
**Usage Examples:**
161
162
```javascript
163
const memoizedFn = memoize(expensiveOperation);
164
165
// Check cache contents
166
if (memoizedFn.cache.has('someKey')) {
167
console.log('Value cached:', memoizedFn.cache.get('someKey'));
168
}
169
170
// Pre-populate cache
171
memoizedFn.cache.set('precomputed', 'precomputed-value');
172
173
// Clear specific cache entry
174
memoizedFn.cache.delete('someKey');
175
176
// Manual cache manipulation
177
const result = memoizedFn('input') || memoizedFn.cache.get('fallback');
178
```
179
180
## Types
181
182
```javascript { .api }
183
/**
184
* MapCache - Default cache implementation
185
* Internal cache object using plain JavaScript object storage
186
*/
187
function MapCache() {
188
this.__data__ = {};
189
}
190
191
/**
192
* Memoized Function Interface
193
* Functions returned by memoize() have an attached cache property
194
*/
195
interface MemoizedFunction extends Function {
196
/** Cache instance for storing memoized results */
197
cache: Cache;
198
}
199
```
200
201
## Error Handling
202
203
The memoize function throws a TypeError in the following cases:
204
205
- When `func` parameter is not a function
206
- When `resolver` parameter is provided but is not a function
207
208
```javascript
209
// This will throw TypeError: Expected a function
210
try {
211
memoize('not-a-function');
212
} catch (error) {
213
console.log(error.message); // "Expected a function"
214
}
215
216
// This will also throw TypeError: Expected a function
217
try {
218
memoize(validFunction, 'not-a-function-resolver');
219
} catch (error) {
220
console.log(error.message); // "Expected a function"
221
}
222
```
223
224
## Advanced Usage Patterns
225
226
### Custom Cache Key Resolution
227
228
```javascript
229
// Hash multiple arguments into a single cache key
230
const complexFunction = (obj, options, callback) => {
231
// expensive computation
232
return processData(obj, options);
233
};
234
235
const memoizedComplex = memoize(complexFunction, (obj, options) => {
236
return JSON.stringify({id: obj.id, opts: options});
237
});
238
```
239
240
### Cache Inspection and Management
241
242
```javascript
243
const memoizedFn = memoize(expensiveComputation);
244
245
// Execute some operations
246
memoizedFn('a');
247
memoizedFn('b');
248
249
// Inspect cache contents
250
console.log('Cache has "a":', memoizedFn.cache.has('a'));
251
console.log('Cached value for "a":', memoizedFn.cache.get('a'));
252
253
// Clear cache selectively
254
memoizedFn.cache.delete('a');
255
```