0
# lodash.memoize
1
2
lodash.memoize provides a memoization function that caches the results of expensive function calls and returns the cached result when the same inputs occur again. It implements an efficient caching mechanism using MapCache with automatic fallbacks for different environments and key types.
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 ES6 modules (if using a bundler):
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 calculation
29
const fibonacci = memoize(function(n) {
30
if (n < 2) return n;
31
return fibonacci(n - 1) + fibonacci(n - 2);
32
});
33
34
// First call - executes the function
35
console.log(fibonacci(10)); // 55 (calculated)
36
37
// Second call - returns cached result
38
console.log(fibonacci(10)); // 55 (from cache)
39
40
// Custom cache key resolver
41
const getUser = memoize(function(id) {
42
return database.fetchUser(id);
43
}, function(id) {
44
return `user_${id}`;
45
});
46
```
47
48
## Capabilities
49
50
### Memoize Function
51
52
Creates a function that memoizes the result of `func`. If `resolver` is provided, it determines the cache key for storing the result based on the arguments provided to the memoized function.
53
54
```javascript { .api }
55
/**
56
* Creates a function that memoizes the result of `func`.
57
* @param {Function} func - The function to have its output memoized
58
* @param {Function} [resolver] - The function to resolve the cache key
59
* @returns {Function} Returns the new memoized function
60
* @throws {TypeError} Throws if `func` is not a function or `resolver` is provided but not a function
61
*/
62
function memoize(func, resolver);
63
```
64
65
**Parameters:**
66
- `func` (Function, required): The function to have its output memoized
67
- `resolver` (Function, optional): The function to resolve the cache key. If not provided, the first argument to the memoized function is used as the cache key
68
69
**Returns:** Function - The new memoized function with a `cache` property
70
71
**Throws:** TypeError - If `func` is not a function or `resolver` is provided but not a function
72
73
**Usage Examples:**
74
75
```javascript
76
// Basic memoization
77
const expensiveOperation = memoize(function(n) {
78
console.log('Computing...');
79
return n * n * n;
80
});
81
82
expensiveOperation(5); // Logs 'Computing...' and returns 125
83
expensiveOperation(5); // Returns 125 from cache (no log)
84
85
// Custom resolver for complex cache keys
86
const getUserData = memoize(function(userId, includeProfile) {
87
return api.fetchUser(userId, includeProfile);
88
}, function(userId, includeProfile) {
89
return `${userId}_${includeProfile}`;
90
});
91
92
// Manual cache manipulation
93
const memoizedFunc = memoize(someFunction);
94
memoizedFunc.cache.set('key', 'value'); // Set cache value
95
memoizedFunc.cache.get('key'); // Get cache value
96
memoizedFunc.cache.has('key'); // Check cache key
97
memoizedFunc.cache.delete('key'); // Remove cache entry
98
```
99
100
### Cache Property
101
102
The memoized function exposes its cache as the `cache` property, allowing for manual cache manipulation.
103
104
```javascript { .api }
105
/**
106
* Cache instance attached to memoized functions
107
* @type {MapCache}
108
*/
109
memoizedFunction.cache;
110
```
111
112
**Methods available on cache:**
113
- `clear()`: Removes all cached entries
114
- `delete(key)`: Removes a specific cache entry, returns boolean
115
- `get(key)`: Gets a cached value by key
116
- `has(key)`: Checks if a key exists in cache, returns boolean
117
- `set(key, value)`: Sets a cache entry, returns the cache instance
118
119
### Cache Constructor
120
121
The default cache constructor used by memoize. Can be replaced with custom cache implementations.
122
123
```javascript { .api }
124
/**
125
* Default cache constructor for memoize
126
* @type {Function}
127
*/
128
memoize.Cache;
129
```
130
131
**Usage:**
132
133
```javascript
134
// Use WeakMap as cache (for object keys only)
135
memoize.Cache = WeakMap;
136
137
const memoizedFunc = memoize(function(obj) {
138
return obj.value * 2;
139
});
140
141
// Use custom cache implementation
142
memoize.Cache = class CustomCache {
143
constructor() {
144
this.data = new Map();
145
}
146
147
get(key) { return this.data.get(key); }
148
set(key, value) { this.data.set(key, value); return this; }
149
has(key) { return this.data.has(key); }
150
delete(key) { return this.data.delete(key); }
151
clear() { this.data.clear(); }
152
};
153
```
154
155
## Types
156
157
```javascript { .api }
158
/**
159
* MapCache - Default cache implementation
160
* Provides efficient caching with automatic fallbacks for different key types
161
*/
162
class MapCache {
163
constructor(entries);
164
clear();
165
delete(key);
166
get(key);
167
has(key);
168
set(key, value);
169
}
170
171
/**
172
* Memoized function type with cache property
173
*/
174
interface MemoizedFunction {
175
(...args: any[]): any;
176
cache: MapCache;
177
}
178
```
179
180
## Advanced Usage
181
182
### Performance Optimization
183
184
```javascript
185
// For recursive functions
186
const fibonacci = memoize(function(n) {
187
if (n < 2) return n;
188
return fibonacci(n - 1) + fibonacci(n - 2);
189
});
190
191
// For API calls with complex parameters
192
const fetchData = memoize(function(params) {
193
return fetch('/api/data', { method: 'POST', body: JSON.stringify(params) });
194
}, function(params) {
195
return JSON.stringify(params); // Serialize complex objects for cache key
196
});
197
```
198
199
### Cache Management
200
201
```javascript
202
const memoizedFunc = memoize(expensiveFunction);
203
204
// Check cache size (not directly available, but can be estimated)
205
console.log(memoizedFunc.cache);
206
207
// Clear cache when needed
208
memoizedFunc.cache.clear();
209
210
// Selective cache clearing
211
if (memoizedFunc.cache.has('outdated-key')) {
212
memoizedFunc.cache.delete('outdated-key');
213
}
214
```
215
216
### Error Handling
217
218
```javascript
219
const safeOperation = memoize(function(input) {
220
if (typeof input !== 'number') {
221
throw new TypeError('Expected a number');
222
}
223
return input * 2;
224
});
225
226
try {
227
safeOperation('invalid'); // Throws TypeError
228
} catch (error) {
229
console.error(error.message); // "Expected a number"
230
}
231
232
// Errors are not cached - subsequent calls with same input will re-throw
233
```