or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

argument-transformation.mdcache-introspection.mdcache-management.mdcore-memoization.mdequality-comparison.mdindex.mdspecialized-memoization.mdstatistics-profiling.mdutility-methods.md

cache-management.mddocs/

0

# Cache Management

1

2

Methods for controlling cache size limits, time-to-live expiration, and argument handling to optimize memory usage and performance.

3

4

## Capabilities

5

6

### Infinite Cache Size

7

8

Remove all limits from cache size, allowing unlimited entries.

9

10

```typescript { .api }

11

/**

12

* Memoization with unlimited cache size

13

* @returns Moizer with no cache size limit

14

*/

15

infinite: Moizer;

16

```

17

18

**Usage Examples:**

19

20

```typescript

21

import moize from "moize";

22

23

const fibonacci = (n: number): number => {

24

if (n < 2) return n;

25

return fibonacci(n - 1) + fibonacci(n - 2);

26

};

27

28

// Cache all fibonacci calculations indefinitely

29

const memoizedFib = moize.infinite(fibonacci);

30

31

console.log(memoizedFib(100)); // All intermediate values cached

32

```

33

34

### Maximum Cache Size

35

36

Set the maximum number of entries that can be stored in the cache.

37

38

```typescript { .api }

39

/**

40

* Set maximum cache size

41

* @param size Maximum number of cache entries

42

* @returns Moizer with specified maximum cache size

43

*/

44

maxSize<MaxSize extends number>(size: MaxSize): Moizer<{ maxSize: MaxSize }>;

45

```

46

47

**Usage Examples:**

48

49

```typescript

50

const expensiveOperation = (data: string) => {

51

// Simulate expensive computation

52

return data.split('').reverse().join('').toUpperCase();

53

};

54

55

// Keep only the 5 most recent results

56

const memoized = moize.maxSize(5)(expensiveOperation);

57

58

// After 6 calls, the first result will be evicted

59

for (let i = 1; i <= 6; i++) {

60

console.log(memoized(`input${i}`));

61

}

62

```

63

64

### Maximum Arguments

65

66

Limit the number of arguments used for determining the cache key.

67

68

```typescript { .api }

69

/**

70

* Limit the number of arguments used for cache key generation

71

* @param args Number of arguments to consider for caching

72

* @returns Moizer with limited argument consideration

73

*/

74

maxArgs<MaxArgs extends number>(args: MaxArgs): Moizer<{ maxArgs: MaxArgs }>;

75

```

76

77

**Usage Examples:**

78

79

```typescript

80

const processData = (

81

primaryData: string,

82

secondaryData: string,

83

debugInfo?: any,

84

metadata?: any

85

) => {

86

return `${primaryData}-${secondaryData}`;

87

};

88

89

// Only use first 2 arguments for caching

90

const memoized = moize.maxArgs(2)(processData);

91

92

console.log(memoized("a", "b", { debug: true }, { env: "prod" })); // Computed

93

console.log(memoized("a", "b", { debug: false }, { env: "dev" })); // Cached (same first 2 args)

94

console.log(memoized("a", "c", { debug: true }, { env: "prod" })); // Computed (different 2nd arg)

95

```

96

97

### Time-to-Live (TTL) with maxAge

98

99

Set expiration time for cached values with comprehensive expiration handling.

100

101

```typescript { .api }

102

interface MaxAge {

103

/**

104

* Set TTL in milliseconds

105

* @param maxAge Time to live in milliseconds

106

* @returns Moizer with TTL configuration

107

*/

108

<MaxAge extends number>(maxAge: MaxAge): Moizer<{ maxAge: MaxAge }>;

109

110

/**

111

* Set TTL with expiration update behavior

112

* @param maxAge Time to live in milliseconds

113

* @param expireOptions Whether to update expiration on cache hit

114

* @returns Moizer with TTL and update expiration configuration

115

*/

116

<MaxAge extends number, UpdateExpire extends boolean>(

117

maxAge: MaxAge,

118

expireOptions: UpdateExpire

119

): Moizer<{ maxAge: MaxAge; updateExpire: UpdateExpire }>;

120

121

/**

122

* Set TTL with expiration callback

123

* @param maxAge Time to live in milliseconds

124

* @param expireOptions Function called when cache entry expires

125

* @returns Moizer with TTL and expiration callback

126

*/

127

<MaxAge extends number, ExpireHandler extends OnExpire>(

128

maxAge: MaxAge,

129

expireOptions: ExpireHandler

130

): Moizer<{ maxAge: MaxAge; onExpire: ExpireHandler }>;

131

132

/**

133

* Set TTL with expiration options object

134

* @param maxAge Time to live in milliseconds

135

* @param expireOptions Configuration object with onExpire and/or updateExpire

136

* @returns Moizer with comprehensive TTL configuration

137

*/

138

<MaxAge extends number, ExpireHandler extends OnExpire, UpdateExpire extends boolean>(

139

maxAge: MaxAge,

140

expireOptions: {

141

onExpire?: ExpireHandler;

142

updateExpire?: UpdateExpire;

143

}

144

): Moizer<{ maxAge: MaxAge; onExpire: ExpireHandler; updateExpire: UpdateExpire }>;

145

}

146

147

type OnExpire = (key: Key) => any;

148

type Key<Arg extends any = any> = Arg[];

149

```

150

151

**Usage Examples:**

152

153

```typescript

154

import moize from "moize";

155

156

// Basic TTL - expire after 5 seconds

157

const fetchData = async (id: string) => {

158

const response = await fetch(`/api/data/${id}`);

159

return response.json();

160

};

161

162

const cachedFetch = moize.maxAge(5000)(fetchData);

163

164

// TTL with expiration update - refresh TTL on each access

165

const memoizedWithRefresh = moize.maxAge(10000, true)(fetchData);

166

167

// TTL with expiration callback

168

const memoizedWithCallback = moize.maxAge(3000, (key) => {

169

console.log(`Cache expired for key:`, key);

170

})(fetchData);

171

172

// TTL with comprehensive options

173

const memoizedComprehensive = moize.maxAge(15000, {

174

updateExpire: true,

175

onExpire: (key) => {

176

console.log(`Expired:`, key);

177

// Could trigger background refresh here

178

}

179

})(fetchData);

180

181

// Using with promise memoization

182

const promiseMemoized = moize.promise.maxAge(30000)(fetchData);

183

```

184

185

### Expiration Management

186

187

Direct control over cache entry expiration.

188

189

```typescript { .api }

190

type Expiration = {

191

/** Function to execute when expiration occurs */

192

expirationMethod: () => void;

193

/** The cache key that will expire */

194

key: Key;

195

/** Timer ID for the expiration timeout */

196

timeoutId: ReturnType<typeof setTimeout>;

197

};

198

```

199

200

### Combining Cache Management Methods

201

202

Cache management methods can be chained together for comprehensive control.

203

204

```typescript

205

import moize from "moize";

206

207

const heavyComputation = (data: any[], options: any) => {

208

return data

209

.filter(options.filter)

210

.map(options.transform)

211

.reduce(options.reduce, options.initialValue);

212

};

213

214

// Combined cache management: size limit, TTL, and argument limit

215

const optimizedMemoized = moize

216

.maxSize(20) // Keep up to 20 entries

217

.maxAge(60000) // Expire after 1 minute

218

.maxArgs(1) // Only use first argument for cache key

219

.deep // Use deep equality for the data array

220

(heavyComputation);

221

222

// With profiling and expiration callback

223

const monitoredMemoized = moize

224

.maxSize(10)

225

.maxAge(30000, {

226

updateExpire: true,

227

onExpire: (key) => console.log('Expired:', key)

228

})

229

.profile('heavy-computation')

230

(heavyComputation);

231

```

232

233

### Cache Size Considerations

234

235

Default cache size is 1, meaning only the most recent result is cached unless explicitly configured.

236

237

```typescript

238

const defaultMemoized = moize(someFunction); // maxSize: 1 by default

239

240

const configuredMemoized = moize(someFunction, {

241

maxSize: 100 // Explicitly set larger cache

242

});

243

244

// Or using fluent API

245

const fluentMemoized = moize.maxSize(100)(someFunction);

246

```