0
# Moize
1
2
Moize is a consistently blazing fast memoization library for JavaScript and TypeScript. It handles multiple parameters without additional configuration and offers comprehensive options for cache management, performance optimization, and specialized use cases including React component memoization and promise caching.
3
4
## Package Information
5
6
- **Package Name**: moize
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install moize`
10
11
## Core Imports
12
13
```typescript
14
import moize from "moize";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const moize = require("moize");
21
```
22
23
For Node.js ESM:
24
25
```typescript
26
import moize from "moize/mjs/index.mjs";
27
```
28
29
## Basic Usage
30
31
```typescript
32
import moize from "moize";
33
34
// Basic function memoization
35
const add = (a: number, b: number) => a + b;
36
const memoizedAdd = moize(add);
37
38
// Memoization with options
39
const fetchUser = async (id: string) => {
40
const response = await fetch(`/api/users/${id}`);
41
return response.json();
42
};
43
const memoizedFetchUser = moize(fetchUser, {
44
isPromise: true,
45
maxSize: 10,
46
maxAge: 30000, // 30 seconds
47
});
48
49
// Using chainable shortcut methods
50
const expensiveCalculation = (data: any[]) => data.reduce((a, b) => a + b.value, 0);
51
const memoizedCalculation = moize.deep.maxSize(5)(expensiveCalculation);
52
53
// React hook pattern (custom implementation)
54
import { useMoize } from './moize-hooks';
55
56
function MyComponent({ first, second }) {
57
const sum = useMoize((a: number, b: number) => a + b, [first, second]);
58
return <div>Sum: {sum}</div>;
59
}
60
```
61
62
## Architecture
63
64
Moize is built around several key components:
65
66
- **Core Memoization Engine**: Built on micro-memoize for high performance with custom equality checking
67
- **Configuration System**: Rich options API supporting equality modes, cache limits, TTL, and callbacks
68
- **Chainable API**: Fluent interface allowing method chaining for common configurations
69
- **Statistics Collection**: Optional performance monitoring with profiling and hit/miss ratios
70
- **React Integration**: Specialized component memoization with props-based caching
71
- **Cache Management**: Direct cache manipulation with introspection capabilities
72
73
## Capabilities
74
75
### Core Memoization
76
77
Main memoization function with extensive configuration options for performance optimization and cache control.
78
79
```typescript { .api }
80
interface Moize<DefaultOptions extends Options<Moizeable> = Options<Moizeable>> {
81
<MoizeableFn extends Moizeable>(fn: MoizeableFn): Moized<MoizeableFn, Options<MoizeableFn> & DefaultOptions>;
82
<MoizeableFn extends Moizeable, PassedOptions extends Options<MoizeableFn>>(
83
fn: MoizeableFn,
84
options: PassedOptions
85
): Moized<MoizeableFn, Options<MoizeableFn> & DefaultOptions & PassedOptions>;
86
<PassedOptions extends Options<Moizeable>>(
87
options: PassedOptions
88
): Moizer<PassedOptions>;
89
}
90
91
type AnyFn = (...args: any[]) => any;
92
type Moizeable = AnyFn & Record<string, any>;
93
```
94
95
[Core Memoization](./core-memoization.md)
96
97
### Equality and Comparison Methods
98
99
Methods for customizing how arguments and cache keys are compared for equality.
100
101
```typescript { .api }
102
interface Moize {
103
deep: Moizer<{ isDeepEqual: true }>;
104
shallow: Moizer<{ isShallowEqual: true }>;
105
matchesArg<Matcher extends IsEqual>(argMatcher: Matcher): Moizer<{ matchesArg: Matcher }>;
106
matchesKey<Matcher extends IsMatchingKey>(keyMatcher: Matcher): Moizer<{ matchesKey: Matcher }>;
107
}
108
109
type IsEqual = (cacheKeyArg: any, keyArg: any) => boolean;
110
type IsMatchingKey = (cacheKey: Key, key: Key) => boolean;
111
type Key<Arg extends any = any> = Arg[];
112
```
113
114
[Equality and Comparison](./equality-comparison.md)
115
116
### Cache Size and TTL Management
117
118
Methods for controlling cache size limits and time-to-live expiration.
119
120
```typescript { .api }
121
interface Moize {
122
infinite: Moizer;
123
maxAge: MaxAge;
124
maxArgs<MaxArgs extends number>(args: MaxArgs): Moizer<{ maxArgs: MaxArgs }>;
125
maxSize<MaxSize extends number>(size: MaxSize): Moizer<{ maxSize: MaxSize }>;
126
}
127
128
interface MaxAge {
129
<MaxAge extends number>(maxAge: MaxAge): Moizer<{ maxAge: MaxAge }>;
130
<MaxAge extends number, UpdateExpire extends boolean>(
131
maxAge: MaxAge,
132
expireOptions: UpdateExpire
133
): Moizer<{ maxAge: MaxAge; updateExpire: UpdateExpire }>;
134
<MaxAge extends number, ExpireHandler extends OnExpire>(
135
maxAge: MaxAge,
136
expireOptions: ExpireHandler
137
): Moizer<{ maxAge: MaxAge; onExpire: ExpireHandler }>;
138
}
139
140
type OnExpire = (key: Key) => any;
141
```
142
143
[Cache Management](./cache-management.md)
144
145
### Specialized Memoization Types
146
147
Specialized memoization methods for specific use cases like promises, React components, and serialization.
148
149
```typescript { .api }
150
interface Moize {
151
promise: Moizer<{ isPromise: true }>;
152
react: Moizer<{ isReact: true }>;
153
serialize: Moizer<{ isSerialized: true }>;
154
serializeWith<Serializer extends Serialize>(serializer: Serializer): Moizer<{ isSerialized: true; serializer: Serializer }>;
155
}
156
157
type Serialize = (key: Key) => string[];
158
```
159
160
[Specialized Memoization](./specialized-memoization.md)
161
162
### Argument Transformation
163
164
Methods for transforming and manipulating arguments before caching.
165
166
```typescript { .api }
167
interface Moize {
168
transformArgs<Transformer extends TransformKey>(transformer: Transformer): Moizer<{ transformArgs: Transformer }>;
169
updateCacheForKey<UpdateWhen extends UpdateCacheForKey>(updateCacheForKey: UpdateWhen): Moizer<{ updateCacheForKey: UpdateWhen }>;
170
}
171
172
type TransformKey = (key: Key) => Key;
173
type UpdateCacheForKey = (key: Key) => boolean;
174
```
175
176
[Argument Transformation](./argument-transformation.md)
177
178
### Statistics and Profiling
179
180
Methods for collecting and analyzing memoization performance statistics.
181
182
```typescript { .api }
183
interface Moize {
184
clearStats(profileName?: string): void;
185
collectStats(isCollectingStats?: boolean): void;
186
getStats(profileName?: string): StatsObject;
187
isCollectingStats(): boolean;
188
profile<ProfileName extends string>(profileName: ProfileName): Moizer<{ profileName: ProfileName }>;
189
}
190
191
type StatsObject = {
192
calls: number;
193
hits: number;
194
usage: string;
195
};
196
197
type GlobalStatsObject = StatsObject & {
198
profiles?: Record<string, StatsProfile>;
199
};
200
201
type StatsProfile = {
202
calls: number;
203
hits: number;
204
};
205
```
206
207
[Statistics and Profiling](./statistics-profiling.md)
208
209
### Cache Introspection and Direct Manipulation
210
211
Methods available on memoized functions for direct cache access and manipulation.
212
213
```typescript { .api }
214
type Moized<MoizeableFn extends Moizeable = Moizeable, CombinedOptions extends Options<MoizeableFn> = Options<MoizeableFn>> =
215
Memoized<MoizeableFn> & {
216
// Properties
217
cache: Cache<MoizeableFn>;
218
cacheSnapshot: Cache<MoizeableFn>;
219
expirations: Expiration[];
220
options: CombinedOptions;
221
originalFunction: MoizeableFn;
222
223
// Cache methods
224
clear(): void;
225
get(key: Key): any;
226
has(key: Key): boolean;
227
remove(key: Key): void;
228
set(key: Key, value: any): void;
229
keys(): Cache<MoizeableFn>['keys'];
230
values(): Cache<MoizeableFn>['values'];
231
232
// Statistics methods
233
clearStats(): void;
234
getStats(): StatsProfile;
235
isCollectingStats(): boolean;
236
237
// Introspection
238
isMoized(): true;
239
};
240
```
241
242
[Cache Introspection](./cache-introspection.md)
243
244
### Utility Methods
245
246
Utility functions for working with memoized functions and composition.
247
248
```typescript { .api }
249
interface Moize {
250
isMoized(value: any): value is Moized;
251
compose(...moizers: Array<Moize | Moizer>): Moizer;
252
}
253
```
254
255
[Utility Methods](./utility-methods.md)
256
257
## Configuration Options
258
259
```typescript { .api }
260
type Options<MoizeableFn extends Moizeable = Moizeable> = Partial<{
261
isDeepEqual: boolean;
262
isPromise: boolean;
263
isReact: boolean;
264
isSerialized: boolean;
265
isShallowEqual: boolean;
266
matchesArg: IsEqual;
267
matchesKey: IsMatchingKey;
268
maxAge: number;
269
maxArgs: number;
270
maxSize: number;
271
onCacheAdd: OnCacheOperation<MoizeableFn>;
272
onCacheChange: OnCacheOperation<MoizeableFn>;
273
onCacheHit: OnCacheOperation<MoizeableFn>;
274
onExpire: OnExpire;
275
profileName: string;
276
serializer: Serialize;
277
transformArgs: TransformKey;
278
updateCacheForKey: UpdateCacheForKey;
279
updateExpire: boolean;
280
}>;
281
282
type OnCacheOperation<MoizeableFn extends Moizeable = Moizeable> = (
283
cache: Cache<MoizeableFn>,
284
options: Options<MoizeableFn>,
285
moized: (...args: any[]) => any
286
) => void;
287
```