forked from ptarjan/node-cache
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
96 lines (78 loc) · 2.06 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
'use strict';
const sizeof = require( 'js-sizeof' );
const TinyCache = function() {
this._cache = {};
this._timeouts = {};
this._hits = 0;
this._misses = 0;
this._size = 0;
return this;
};
TinyCache.prototype = {
get size() {
return this._size;
},
get memsize() {
return sizeof( this._cache ); /* Returns the approximate memory usage of all objects stored in the cache and cache overhead */
},
get hits() {
return this._hits;
},
get misses() {
return this._misses;
},
put: function( key, value, time ) {
if ( this._timeouts[ key ] ) {
clearTimeout( this._timeouts[ key ] );
delete this._timeouts[ key ];
}
this._cache[ key ] = value;
if ( !isNaN( time ) ) {
this._timeouts[ key ] = setTimeout( this.del.bind( this, key ), time );
}
++this._size;
},
get: function( key ) {
if ( typeof key === 'undefined' ) {
return this._cache;
}
if ( !( key in this._cache ) ) {
++this._misses;
return null;
}
++this._hits;
return this._cache[ key ];
},
del: function( key ) {
clearTimeout( this._timeouts[ key ] );
delete this._timeouts[ key ];
if ( !( key in this._cache ) ) {
return false;
}
delete this._cache[ key ];
--this._size;
return true;
},
clear: function() {
for ( let key in this._timeouts ) {
clearTimeout( this._timeouts[ key ] );
}
this._cache = {};
this._timeouts = {};
this._size = 0;
}
};
TinyCache.shared = new TinyCache();
if ( typeof module !== 'undefined' && module.exports ) {
module.exports = TinyCache;
}
else if ( typeof define === 'function' && define.amd ) {
/* global define */
define( [], function() {
return TinyCache;
} );
}
else {
/* global window */
window.TinyCache = TinyCache;
}