0
# Memoizee
1
2
Memoizee is a comprehensive memoization/caching solution for JavaScript functions that provides intelligent function result caching to optimize performance and reduce computational overhead. It supports any type of function arguments without requiring serialization, handles variable-length arguments, works with asynchronous functions and promises, and offers advanced features like cache expiration, LRU-based cache limiting, and sophisticated cache management.
3
4
## Package Information
5
6
- **Package Name**: memoizee
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install memoizee`
10
11
## Core Imports
12
13
```javascript
14
const memoize = require("memoizee");
15
```
16
17
For ES modules:
18
19
```javascript
20
import memoize from "memoizee";
21
```
22
23
## Basic Usage
24
25
```javascript
26
const memoize = require("memoizee");
27
28
// Basic function memoization
29
function expensiveFunction(x, y) {
30
console.log("Computing...");
31
return x * y * Math.random();
32
}
33
34
const memoized = memoize(expensiveFunction);
35
36
memoized(3, 4); // Computes and caches result
37
memoized(3, 4); // Returns cached result (no "Computing..." log)
38
```
39
40
## Architecture
41
42
Memoizee is built around several key components:
43
44
- **Core Memoization**: Main `memoize` function that creates cached versions of functions
45
- **Configuration System**: Extensive options for customizing caching behavior and performance characteristics
46
- **Extension Architecture**: Modular extensions for async functions, promises, cache expiration, and advanced features
47
- **Multiple Cache Strategies**: Support for primitive mode, object mode, and WeakMap-based caching
48
- **Cache Management**: Manual cache control, automatic expiration, LRU eviction, and reference counting
49
50
## Capabilities
51
52
### Function Memoization
53
54
Core memoization functionality that wraps functions to cache their results based on input arguments. Supports configurable argument handling, custom cache key generation, and multiple caching strategies.
55
56
```javascript { .api }
57
/**
58
* Create a memoized version of a function
59
* @param {Function} fn - Function to memoize
60
* @param {Object} options - Configuration options
61
* @returns {Function} Memoized function with cache management methods
62
*/
63
function memoize(fn, options);
64
```
65
66
[Function Memoization](./function-memoization.md)
67
68
### Asynchronous Function Support
69
70
Specialized memoization for Node.js callback-style functions and promise-returning functions. Handles error cases, prevents caching of failed operations, and supports multiple promise handling modes.
71
72
```javascript { .api }
73
// For callback-style async functions
74
const memoizedAsync = memoize(asyncFn, { async: true });
75
76
// For promise-returning functions
77
const memoizedPromise = memoize(promiseFn, { promise: true });
78
```
79
80
[Asynchronous Functions](./async-functions.md)
81
82
### Cache Management
83
84
Advanced cache control features including manual cache manipulation, automatic expiration with pre-fetching, LRU-based size limiting, and reference counting for sophisticated memory management.
85
86
```javascript { .api }
87
// Cache manipulation methods available on memoized functions
88
memoized.delete(...args); // Delete specific cache entry
89
memoized.clear(); // Clear all cached entries
90
memoized._get(...args); // Get cached value without triggering execution
91
memoized._has(...args); // Check if arguments have cached result
92
```
93
94
[Cache Management](./cache-management.md)
95
96
### WeakMap-Based Memoization
97
98
Memory-efficient memoization using WeakMap for garbage collection friendly caching when the first argument is expected to be an object. Cache entries are automatically garbage collected when objects are no longer referenced.
99
100
```javascript { .api }
101
const weakMemoize = require("memoizee/weak");
102
103
const memoized = weakMemoize(function(obj) {
104
return Object.keys(obj).length;
105
});
106
```
107
108
[WeakMap Memoization](./weakmap-memoization.md)
109
110
### Method Memoization
111
112
Specialized utilities for memoizing object methods with lazy property descriptors and proper `this` context handling. Ideal for prototype method optimization and instance-specific caching.
113
114
```javascript { .api }
115
const memoizeMethods = require("memoizee/methods");
116
117
// Usage with property descriptors
118
Object.defineProperties(MyClass.prototype, memoizeMethods({
119
expensiveMethod: d(function() { /* method logic */ }, { maxAge: 1000 })
120
}));
121
```
122
123
[Method Memoization](./method-memoization.md)
124
125
### Performance Profiling
126
127
Built-in profiling and statistics system that provides detailed insights into cache performance, hit rates, and function call patterns. Essential for optimizing memoization strategies and identifying performance bottlenecks.
128
129
```javascript { .api }
130
const memProfile = require("memoizee/profile");
131
132
// Profile statistics and logging
133
memProfile.statistics; // Raw statistics object
134
memProfile.log(); // Formatted statistics report
135
```
136
137
[Performance Profiling](./profiling.md)
138
139
## Configuration Options
140
141
```javascript { .api }
142
interface MemoizeOptions {
143
// Argument handling
144
length?: number | false; // Override function argument length
145
primitive?: boolean; // Use primitive mode for string-convertible args
146
normalizer?: Function; // Custom cache key normalization
147
resolvers?: Function[]; // Argument type coercion functions
148
149
// Asynchronous support
150
async?: boolean; // Enable for Node.js callback functions
151
promise?: boolean | string; // Enable for promise functions ("then", "done", etc.)
152
153
// Cache expiration
154
maxAge?: number; // Cache TTL in milliseconds
155
preFetch?: boolean | number; // Pre-fetch ratio for cache refresh
156
157
// Cache size management
158
max?: number; // Maximum cache entries (LRU eviction)
159
160
// Advanced features
161
refCounter?: boolean; // Enable reference counting
162
dispose?: Function; // Callback for cache entry disposal
163
force?: boolean; // Force re-memoization of memoized functions
164
profileName?: string; // Name for profiling identification
165
}
166
```
167
168
## Common Patterns
169
170
### High-Performance Caching
171
172
For functions with primitive arguments that convert to unique strings:
173
174
```javascript
175
const memoized = memoize(fn, { primitive: true });
176
```
177
178
### Memory-Conscious Caching
179
180
For object-based functions with automatic cleanup:
181
182
```javascript
183
const weakMemoize = require("memoizee/weak");
184
const memoized = weakMemoize(fn);
185
```
186
187
### Time-Based Cache Invalidation
188
189
For functions that need fresh data periodically:
190
191
```javascript
192
const memoized = memoize(fn, {
193
maxAge: 60000, // 1 minute TTL
194
preFetch: 0.33 // Refresh when 33% of TTL remains
195
});
196
```
197
198
### Size-Limited Cache
199
200
For functions with potentially unlimited input variations:
201
202
```javascript
203
const memoized = memoize(fn, {
204
max: 100, // Keep only 100 most recent results
205
dispose: cleanup // Custom cleanup for evicted entries
206
});
207
```