-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
657 lines (575 loc) · 24.3 KB
/
index.js
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
/**
* Fixed size cache storing key-value pairs such that total
* byte size of stored values will not exceed given limit.
* Uses the LFU algortihm (least frequently used) to evict entries if cache is full.
* Additionally an expire interval can be set (passive on {@code put()} call) that repeatedly halfs
* the access counter of each entry.
* @author LupCode.com
*/
class FixedSizeLFUCache {
#maxSize;
#expireMs;
#size = 0;
#entries = {}; // key: {value: Object, size: int, accesses: int, onEvict: function}
#nextExpire;
/**
* Creates a new cache with a fixed storing capacity
* @param {Number} maxSizeMB Limit how many mega bytes cache can store
* @param {int} expireMs If >= 0 expire interval in milliseconds at which access counters are halfed
*/
constructor(maxSizeMB, expireMs=60000){
this.#maxSize = Math.floor(maxSizeMB * 1024 * 1024);
this.#expireMs = Math.floor(expireMs);
this.#nextExpire = Date.now() + this.#expireMs;
}
/**
* @returns Amount of key-value pairs stored in cache
*/
getCount(){
return Object.keys(this.#entries).length;
}
/**
* @returns Total size of stored entries in mega bytes
*/
getSizeInMB(){
return this.#size / 1024 / 1024;
}
/**
* @returns Maximum total size of stored entries in mega bytes
*/
getMaxSizeMB(){
return this.#maxSize / 1024 / 1024;
}
/**
* Sets the maximum size the total byte size of all values is not allowed to exceed
* @param {Number} maxSizeMB Maximum byte size of all values in mega byte
*/
setMaxSizeMB(maxSizeMB){
this.#maxSize = parseInt(maxSizeMB * 1024 * 1024);
}
/**
* @returns Milliseconds interval at which the access counter of entry entry gets halfed (negative means disabled)
*/
getExpireTime(){
return this.#expireMs;
}
/**
* Sets the interval at which the access counter of each entry gets halfed
* @param {int} expireMs Milliseconds of interval at which the access counters of all entries are halfed (negative means disabled)
*/
setExpireTime(expireMs){
this.#expireMs = parseInt(expireMs);
}
/**
* Puts a key-value pair into cache
* @param {String} key Unique key to reference value in cache
* @param {*} value Value that should be put into cache
* @param {Object} options Additional options that can be set:
* - size: int Size in bytes of value (if value is {@type String} or {@type Buffer} size parameter not required)
* - onEvict: Function Callback that gets called with key and value that were evicted from cache (if returns {@code false} pair does not get evicted)
* @returns True if successfully put key-value pair into cache or false if value is too big to fit into cache
* @throws Error if size is not given while value is not of type String nor of type Buffer
*/
put(key, value, options={size: undefined, onEvict: function(k,v){}}){
if(!key || (typeof key !== 'string' && !(key instanceof String))) throw new Error("Key must be defined and of type String");
if(!options.size){
if(typeof key === 'string' || value instanceof String || value instanceof Buffer){
options.size = Buffer.byteLength(value);
} else {
throw Error("Byte size must be provided for a value of type " + (typeof value));
}
}
if(options.size > this.#maxSize) return false;
// half all 'access' counters if expired
if(this.#expireMs >= 0){
const now = Date.now();
if(this.#nextExpire < now){
this.#nextExpire = now + this.#expireMs;
for(let v of Object.values(this.#entries)) v.accesses = Math.floor(v.accesses / 2);
}
}
// evict entries until enough space is available for new entry
if(this.#maxSize - this.#size < options.size){
let sorted = Object.entries(this.#entries).sort(function([, a], [, b]){ return a.accesses-b.accesses; });
let index = 0;
while(index < sorted.length && this.#maxSize - this.#size < options.size) {
let entry = sorted[index++];
if(entry[1].onEvict && entry[1].onEvict(entry[0], entry[1].value) === false) continue;
this.#size -= entry[1].size;
delete this.#entries[entry[0]];
}
if(this.#maxSize - this.#size < options.size) return false;
}
// put new entry into cache
this.#size += options.size;
this.#entries[key] = {
value: value,
size: options.size,
accesses: 1,
onEvict: options.onEvict
};
return true;
}
/**
* Returns a value from the cache by its key (if it is still in the cache)
* @param {String} key Key of the value that should be returned
* @returns Value if found or undefined if not found
*/
get(key){
let entry = this.#entries[key];
if(!entry) return undefined;
entry.accesses++;
return entry.value;
}
/**
* Removes a key-value pair from the cache immediatly.
* Will not trigger the onEvict callback if defined.
* @param {String} key Key of the value that should be removed
* @returns Value of the removed key-value pair or undefined if not found
*/
remove(key){
let entry = this.#entries[key];
if(!entry) return undefined;
this.#size -= entry.size;
let value = entry.value;
delete this.#entries[key];
return value;
}
/**
* Clears the cache without calling the {@code onEvict} callbacks (by default)
* @param {bool} callEvictCallbacks If {@code true} for each entry the {@code onEvict} callback will be called
* which can prevent evicting the entry by returning {@type false}.
*/
clear(callEvictCallbacks=false){
for(let entry of Object.entries(this.#entries)){
if(callEvictCallbacks && entry[1].onEvict && entry[1].onEvict(entry[0], entry[1].value) === false) continue;
this.remove(entry[0]);
}
}
/**
* @returns String containing basic information about this cache
*/
toString(){
return this.constructor.name + "{size=" + Number(this.getSizeInMB()).toFixed(2) + "/" + Number(this.getMaxSizeMB()).toFixed(2) +
"MB; entries=" + this.getCount() + "; expireInterval=" + this.getExpireTime() + "}";
}
}
/**
* Cache storing fixed amount of key-value pairs.
* Uses the LFU algortihm (least frequently used) to evict entries if cache is full.
* Additionally an expire interval can be set (passive on {@code put()} call) that repeatedly halfs
* the access counter of each entry.
* @author LupCode.com
*/
class FixedCountLFUCache {
#maxCount;
#count = 0;
#expireMs;
#entries = {}; // key: {value: Object, accesses: int, onEvict: function}
#nextExpire;
/**
* Creates a new cache with a fixed storing capacity
* @param {Number} maxCount Maximum amount of key-value pairs that can be hold
* @param {int} expireMs If >= 0 expire interval in milliseconds at which access counters are halfed
*/
constructor(maxCount, expireMs=5000){
this.#maxCount = parseInt(maxCount);
this.#expireMs = parseInt(expireMs);
this.#nextExpire = Date.now() + this.#expireMs;
}
/**
* @returns Amount of key-value pairs stored in cache
*/
getCount(){
return this.#count;
}
/**
* @returns Maximum amount of key-value pairs that can be hold
*/
getMaxCount(){
return this.#maxCount;
}
/**
* Sets the maximum amount of entries the cache can hold
* @param {int} maxCount Maximum amount of key-value pairs
*/
setMaxCount(maxCount){
this.#maxCount = parseInt(maxCount);
}
/**
* @returns Milliseconds interval at which the access counter of entry entry gets halfed (negative means disabled)
*/
getExpireTime(){
return this.#expireMs;
}
/**
* Sets the interval at which the access counter of each entry gets halfed
* @param {int} expireMs Milliseconds of interval at which the access counters of all entries are halfed (negative means disabled)
*/
setExpireTime(expireMs){
this.#expireMs = parseInt(expireMs);
}
/**
* Puts a key-value pair into cache
* @param {String} key Unique key to reference value in cache
* @param {*} value Value that should be put into cache
* @param {Object} options Additional options that can be set:
* - onEvict: Function Callback that gets called with key and value that were evicted from cache (if returns {@code false} pair does not get evicted)
* @returns True if successfully put key-value pair into cache or false if value is too big to fit into cache
*/
put(key, value, options={onEvict: function(k,v){}}){
if(!key || (typeof key !== 'string' && !(key instanceof String))) throw new Error("Key must be defined and of type String");
// half all 'access' counters if expired
if(this.#expireMs >= 0){
const now = Date.now();
if(this.#nextExpire < now){
this.#nextExpire = now + this.#expireMs;
for(let v of Object.values(this.#entries)) v.accesses = Math.floor(v.accesses / 2);
}
}
// evict entries until enough space is available for new entry
if(this.#count >= this.#maxCount){
let sorted = Object.entries(this.#entries).sort(function([, a], [, b]){ return a.accesses-b.accesses; });
let index = 0;
while(index < sorted.length && this.#count >= this.#maxCount) {
let entry = sorted[index++];
if(entry[1].onEvict && entry[1].onEvict(entry[0], entry[1].value) === false) continue;
this.#count--;
delete this.#entries[entry[0]];
}
if(this.#count >= this.#maxCount) return false;
}
// put new entry into cache
this.#entries[key] = {
value: value,
accesses: 1,
onEvict: options.onEvict
};
this.#count++;
return true;
}
/**
* Returns a value from the cache by its key (if it is still in the cache)
* @param {String} key Key of the value that should be returned
* @returns Value if found or undefined if not found
*/
get(key){
let entry = this.#entries[key];
if(!entry) return undefined;
entry.accesses++;
return entry.value;
}
/**
* Removes a key-value pair from the cache immediatly.
* Will not trigger the onEvict callback if defined.
* @param {String} key Key of the value that should be removed
* @returns Value of the removed key-value pair or undefined if not found
*/
remove(key){
let entry = this.#entries[key];
if(!entry) return undefined;
this.#count--;
let value = entry.value;
delete this.#entries[key];
return value;
}
/**
* Clears the cache without calling the {@code onEvict} callbacks (by default)
* @param {bool} callEvictCallbacks If {@code true} for each entry the {@code onEvict} callback will be called
* which can prevent evicting the entry by returning {@type false}.
*/
clear(callEvictCallbacks=false){
for(let entry of Object.entries(this.#entries)){
if(callEvictCallbacks && entry[1].onEvict && entry[1].onEvict(entry[0], entry[1].value) === false) continue;
delete this.#entries[entry[0]];
}
}
/**
* @returns String containing basic information about this cache
*/
toString(){
return this.constructor.name + "{entries=" + this.getCount() + "/" + this.getMaxCount() + "; expireInterval=" + this.getExpireTime() + "ms}";
}
}
/**
* Fixed size cache storing key-value pairs such that total
* byte size of stored values will not exceed given limit.
* Uses the LRU algortihm (least recently used) to evict entries if cache is full.
* Cheaper and faster than LFU but not as many cache hits.
* @author LupCode.com
*/
class FixedSizeLRUCache {
#maxSize;
#size = 0;
#head = null; // string
#tail = null; // string
#entries = {}; // key: {value: Object, size: int, prev: String, next: String, onEvict: function}
/**
* Creates a new cache with a fixed storing capacity
* @param {Number} maxSizeMB Limit how many mega bytes cache can store
*/
constructor(maxSizeMB){
this.#maxSize = Math.floor(maxSizeMB * 1024 * 1024);
}
/**
* @returns Amount of key-value pairs stored in cache
*/
getCount(){
return Object.keys(this.#entries).length;
}
/**
* @returns Total size of stored entries in mega bytes
*/
getSizeInMB(){
return this.#size / 1024 / 1024;
}
/**
* @returns Maximum total size of stored entries in mega bytes
*/
getMaxSizeMB(){
return this.#maxSize / 1024 / 1024;
}
/**
* Sets the maximum size the total byte size of all values is not allowed to exceed
* @param {Number} maxSizeMB Maximum byte size of all values in mega byte
*/
setMaxSizeMB(maxSizeMB){
this.#maxSize = parseInt(maxSizeMB * 1024 * 1024);
}
/**
* Puts a key-value pair into cache
* @param {String} key Unique key to reference value in cache
* @param {*} value Value that should be put into cache
* @param {Object} options Additional options that can be set:
* - size: int Size in bytes of value (if value is {@type String} or {@type Buffer} size parameter not required)
* - onEvict: Function Callback that gets called with key and value that were evicted from cache (if returns {@code false} pair does not get evicted)
* @returns True if successfully put key-value pair into cache or false if value is too big to fit into cache
* @throws Error if size is not given while value is not of type String nor of type Buffer
*/
put(key, value, options={size: undefined, onEvict: function(k,v){}}){
if(!key || (typeof key !== 'string' && !(key instanceof String))) throw new Error("Key must be defined and of type String");
if(!options.size){
if(typeof key === 'string' || value instanceof String || value instanceof Buffer){
options.size = Buffer.byteLength(value);
} else {
throw Error("Byte size must be provided for a value of type " + (typeof value));
}
}
if(options.size > this.#maxSize) return false;
// evict entries until enough space is available for new entry
if(this.#maxSize - this.#size < options.size){
let curr = this.#head;
while(curr && this.#maxSize - this.#size < options.size) {
let entry = this.#entries[curr];
if(entry.onEvict && entry.onEvict(this.#head, entry.value) === false){ curr = entry.next; continue; }
this.#size -= entry.size;
if(entry.prev) this.#entries[entry.prev].next = entry.next; else this.#head = entry.next;
if(entry.next) this.#entries[entry.next].prev = entry.prev; else this.#tail = entry.prev;
let nextKey = entry.next;
delete this.#entries[curr];
if(curr == this.#head) this.#head = nextKey;
curr = nextKey;
}
if(this.#maxSize - this.#size < options.size) return false;
}
// put new entry into cache
this.#size += options.size;
this.#entries[key] = {
value: value,
size: options.size,
prev: this.#tail,
next: null,
onEvict: options.onEvict
};
if(!this.#head) this.#head = key;
if(this.#tail) this.#entries[this.#tail].next = key;
this.#tail = key;
return true;
}
/**
* Returns a value from the cache by its key (if it is still in the cache)
* @param {String} key Key of the value that should be returned
* @returns Value if found or undefined if not found
*/
get(key){
let entry = this.#entries[key];
if(!entry) return undefined;
if(key == this.#tail) return entry.value;
if(entry.prev) this.#entries[entry.prev].next = entry.next; else this.#head = entry.next;
if(entry.next) this.#entries[entry.next].prev = entry.prev; else this.#tail = entry.prev;
entry.next = null;
entry.prev = this.#tail;
if(this.#tail) this.#entries[this.#tail].next = key;
this.#tail = key;
return entry.value;
}
/**
* Removes a key-value pair from the cache immediatly.
* Will not trigger the onEvict callback if defined.
* @param {String} key Key of the value that should be removed
* @returns Value of the removed key-value pair or undefined if not found
*/
remove(key){
let entry = this.#entries[key];
if(!entry) return undefined;
this.#size -= entry.size;
if(entry.prev) this.#entries[entry.prev].next = entry.next; else this.#head = entry.next;
if(entry.next) this.#entries[entry.next].prev = entry.prev; else this.#tail = entry.prev;
let value = entry.value;
delete this.#entries[key];
return value;
}
/**
* Clears the cache without calling the {@code onEvict} callbacks (by default)
* @param {bool} callEvictCallbacks If {@code true} for each entry the {@code onEvict} callback will be called
* which can prevent evicting the entry by returning {@type false}.
*/
clear(callEvictCallbacks=false){
for(let entry of Object.entries(this.#entries)){
if(callEvictCallbacks && entry[1].onEvict && entry[1].onEvict(entry[0], entry[1].value) === false) continue;
this.remove(entry[0]);
}
}
/**
* @returns String containing basic information about this cache
*/
toString(){
return this.constructor.name + "{size=" + Number(this.getSizeInMB()).toFixed(2) + "/" + Number(this.getMaxSizeMB()).toFixed(2) +
"MB; entries=" + this.getCount() + "}";
}
}
/**
* Cache storing fixed amount of key-value pairs.
* Uses the LRU algortihm (least recently used) to evict entries if cache is full.
* Cheaper and faster than LFU but not as many cache hits.
* @author LupCode.com
*/
class FixedCountLRUCache {
#maxCount;
#count = 0;
#head = null; // string
#tail = null; // string
#entries = {}; // key: {value: Object, size: int, prev: String, next: String, onEvict: function}
/**
* Creates a new cache with a fixed storing capacity
* @param {Number} maxCount Maximum amount of key-value pairs that can be hold
*/
constructor(maxCount){
this.#maxCount = parseInt(maxCount);
}
/**
* @returns Amount of key-value pairs stored in cache
*/
getCount(){
return this.#count;
}
/**
* @returns Maximum amount of key-value pairs that can be hold
*/
getMaxCount(){
return this.#maxCount;
}
/**
* Sets the maximum amount of entries the cache can hold
* @param {int} maxCount Maximum amount of key-value pairs
*/
setMaxCount(maxCount){
this.#maxCount = parseInt(maxCount);
}
/**
* Puts a key-value pair into cache
* @param {String} key Unique key to reference value in cache
* @param {*} value Value that should be put into cache
* @param {Object} options Additional options that can be set:
* - onEvict: Function Callback that gets called with key and value that were evicted from cache (if returns {@code false} pair does not get evicted)
* @returns True if successfully put key-value pair into cache or false if value is too big to fit into cache
* @throws Error if size is not given while value is not of type String nor of type Buffer
*/
put(key, value, options={onEvict: function(k,v){}}){
if(!key || (typeof key !== 'string' && !(key instanceof String))) throw new Error("Key must be defined and of type String");
// evict entries until enough space is available for new entry
if(this.#count >= this.#maxCount){
let curr = this.#head;
while(curr && this.#count >= this.#maxCount) {
let entry = this.#entries[curr];
if(entry.onEvict && entry.onEvict(this.#head, entry.value) === false){ curr = entry.next; continue; }
if(entry.prev) this.#entries[entry.prev].next = entry.next; else this.#head = entry.next;
if(entry.next) this.#entries[entry.next].prev = entry.prev; else this.#tail = entry.prev;
this.#count--;
let nextKey = entry.next;
delete this.#entries[curr];
if(curr == this.#head) this.#head = nextKey;
curr = nextKey;
}
if(this.#count >= this.#maxCount) return false;
}
// put new entry into cache
this.#entries[key] = {
value: value,
prev: this.#tail,
next: null,
onEvict: options.onEvict
};
this.#count++;
if(!this.#head) this.#head = key;
if(this.#tail) this.#entries[this.#tail].next = key;
this.#tail = key;
return true;
}
/**
* Returns a value from the cache by its key (if it is still in the cache)
* @param {String} key Key of the value that should be returned
* @returns Value if found or undefined if not found
*/
get(key){
let entry = this.#entries[key];
if(!entry) return undefined;
if(key == this.#tail) return entry.value;
if(entry.prev) this.#entries[entry.prev].next = entry.next; else this.#head = entry.next;
if(entry.next) this.#entries[entry.next].prev = entry.prev; else this.#tail = entry.prev;
entry.next = null;
entry.prev = this.#tail;
if(this.#tail) this.#entries[this.#tail].next = key;
this.#tail = key;
return entry.value;
}
/**
* Removes a key-value pair from the cache immediatly.
* Will not trigger the onEvict callback if defined.
* @param {String} key Key of the value that should be removed
* @returns Value of the removed key-value pair or undefined if not found
*/
remove(key){
let entry = this.#entries[key];
if(!entry) return undefined;
if(entry.prev) this.#entries[entry.prev].next = entry.next; else this.#head = entry.next;
if(entry.next) this.#entries[entry.next].prev = entry.prev; else this.#tail = entry.prev;
this.#count--;
let value = entry.value;
delete this.#entries[key];
return value;
}
/**
* Clears the cache without calling the {@code onEvict} callbacks (by default)
* @param {bool} callEvictCallbacks If {@code true} for each entry the {@code onEvict} callback will be called
* which can prevent evicting the entry by returning {@type false}.
*/
clear(callEvictCallbacks=false){
for(let entry of Object.entries(this.#entries)){
if(callEvictCallbacks && entry[1].onEvict && entry[1].onEvict(entry[0], entry[1].value) === false) continue;
this.remove(entry[0]);
}
}
/**
* @returns String containing basic information about this cache
*/
toString(){
return this.constructor.name + "{entries=" + this.getCount() + "/" + this.getMaxCount() + "}";
}
}
module.exports = {
FixedSizeLFUCache,
FixedCountLFUCache,
FixedSizeLRUCache,
FixedCountLRUCache
}