-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperformance-cache.js
More file actions
316 lines (274 loc) · 7.67 KB
/
Copy pathperformance-cache.js
File metadata and controls
316 lines (274 loc) · 7.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/**
* Performance Cache Module
* LRU cache with TTL support for expensive calculations
*/
class PerformanceCache {
/**
* @param {number} maxSize - maximum number of entries to keep
* @param {number} defaultTTL - time-to-live in milliseconds (default 5 minutes)
* @param {object} options - { cleanupIntervalMs, disableAutoCleanup }
*/
constructor(maxSize = 100, defaultTTL = 300000, options = {}) {
this.cache = new Map();
this.maxSize = maxSize;
this.defaultTTL = defaultTTL;
this.accessOrder = []; // Track access order for LRU
this._cleanupTimer = null;
this.cleanupIntervalMs = options.cleanupIntervalMs || Math.min(60000, Math.floor(defaultTTL / 2));
if (!options.disableAutoCleanup) {
this._startCleanup();
}
}
/**
* Start background cleanup timer (unref'd so it won't keep Node alive)
*/
_startCleanup() {
if (this._cleanupTimer) return;
this._cleanupTimer = setInterval(() => this.clearExpired(), this.cleanupIntervalMs);
// Allow Node to exit even if this timer exists
if (this._cleanupTimer && typeof this._cleanupTimer.unref === 'function') {
this._cleanupTimer.unref();
}
}
/**
* Stop the background cleanup timer
*/
stop() {
if (this._cleanupTimer) {
clearInterval(this._cleanupTimer);
this._cleanupTimer = null;
}
}
/**
* Generate cache key from multiple parameters
*/
generateKey(...params) {
return JSON.stringify(params);
}
/**
* Get value from cache
*/
get(key) {
const entry = this.cache.get(key);
if (!entry) {
return null;
}
// Check if expired
if (Date.now() > entry.expiry) {
this.cache.delete(key);
this.removeFromAccessOrder(key);
return null;
}
// Update access order (LRU)
this.updateAccessOrder(key);
return entry.value;
}
/**
* Set value in cache
*/
set(key, value, ttl = this.defaultTTL) {
// Evict oldest if cache is full
if (this.cache.size >= this.maxSize && !this.cache.has(key)) {
const oldestKey = this.accessOrder[0];
this.cache.delete(oldestKey);
this.accessOrder.shift();
}
this.cache.set(key, {
value,
expiry: Date.now() + ttl
});
this.updateAccessOrder(key);
}
/**
* Check if key exists and is not expired
*/
has(key) {
return this.get(key) !== null;
}
/**
* Clear entire cache
*/
clear() {
this.cache.clear();
this.accessOrder = [];
}
/**
* Clear expired entries
*/
clearExpired() {
const now = Date.now();
for (const [key, entry] of this.cache.entries()) {
if (now > entry.expiry) {
this.cache.delete(key);
this.removeFromAccessOrder(key);
}
}
}
/**
* Update access order for LRU
*/
updateAccessOrder(key) {
this.removeFromAccessOrder(key);
this.accessOrder.push(key);
}
/**
* Remove key from access order
*/
removeFromAccessOrder(key) {
const index = this.accessOrder.indexOf(key);
if (index > -1) {
this.accessOrder.splice(index, 1);
}
}
/**
* Get cache statistics
*/
getStats() {
return {
size: this.cache.size,
maxSize: this.maxSize,
hitRate: this.hits / (this.hits + this.misses) || 0,
hits: this.hits || 0,
misses: this.misses || 0
};
}
/**
* Memoize a function with caching
*/
memoize(fn, keyFn, ttl) {
return (...args) => {
const key = keyFn ? keyFn(...args) : this.generateKey(...args);
let result = this.get(key);
if (result === null) {
result = fn(...args);
this.set(key, result, ttl);
this.misses = (this.misses || 0) + 1;
} else {
this.hits = (this.hits || 0) + 1;
}
return result;
};
}
}
/**
* Date utilities for performance optimization
*/
class DateUtils {
/**
* Pre-compute date key from timestamp
* Returns ISO date string (YYYY-MM-DD)
*/
static toDateKey(timestamp) {
if (!timestamp) return null;
return typeof timestamp === 'string'
? timestamp.split('T')[0]
: new Date(timestamp).toISOString().split('T')[0];
}
/**
* Get cutoff date for filtering
*/
static getCutoffDate(days) {
const cutoff = new Date();
cutoff.setDate(cutoff.getDate() - days);
cutoff.setHours(0, 0, 0, 0);
return cutoff;
}
/**
* Check if date is within range
*/
static isWithinDays(timestamp, days) {
const cutoff = this.getCutoffDate(days);
const date = new Date(timestamp);
return date >= cutoff;
}
/**
* Batch process dates - add dateKey to entries
*/
static addDateKeys(entries) {
return entries.map(entry => ({
...entry,
dateKey: this.toDateKey(entry.timestamp || entry.date)
}));
}
/**
* Group entries by date
*/
static groupByDate(entries, dateField = 'timestamp') {
const groups = new Map();
entries.forEach(entry => {
const dateKey = this.toDateKey(entry[dateField]);
if (!groups.has(dateKey)) {
groups.set(dateKey, []);
}
groups.get(dateKey).push(entry);
});
return groups;
}
}
/**
* Array optimization utilities
*/
class ArrayUtils {
/**
* Single-pass multi-filter
* Instead of: arr.filter(a).filter(b).filter(c)
* Use: singlePassFilter(arr, [filterA, filterB, filterC])
*/
static singlePassMultiFilter(array, predicates) {
return array.filter(item => predicates.every(pred => pred(item)));
}
/**
* Single-pass grouping and counting
* Replaces multiple filter operations for counting
*/
static groupAndCount(array, keyFn, valueFns = {}) {
const result = {};
array.forEach(item => {
const key = keyFn(item);
if (!result[key]) {
result[key] = { count: 0 };
Object.keys(valueFns).forEach(vKey => {
result[key][vKey] = [];
});
}
result[key].count++;
Object.entries(valueFns).forEach(([vKey, vFn]) => {
result[key][vKey].push(vFn(item));
});
});
return result;
}
/**
* Create lookup Map from array
* O(1) lookups instead of O(n) find()
*/
static createLookupMap(array, keyFn) {
return new Map(array.map(item => [keyFn(item), item]));
}
/**
* Paginate array
*/
static paginate(array, page = 1, pageSize = 50) {
const startIndex = (page - 1) * pageSize;
const endIndex = startIndex + pageSize;
return {
data: array.slice(startIndex, endIndex),
page,
pageSize,
total: array.length,
totalPages: Math.ceil(array.length / pageSize),
hasMore: endIndex < array.length
};
}
/**
* Limit array size for performance
*/
static limit(array, maxSize = 1000) {
return array.length > maxSize ? array.slice(-maxSize) : array;
}
}
module.exports = {
PerformanceCache,
DateUtils,
ArrayUtils
};