-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
140 lines (109 loc) · 2.27 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
/**
* JSMemcache
*
* Store data in memory for better performance
* by saving on network requests.
*
* @author Jabran Rafique <hello@jabran.me>
* @license MIT
*/
let _cache = {};
let _limit = 100;
let _separator = '+';
let _isOverLimit = false;
let _size = 0;
class JSMemcache {
constructor() {
return this;
}
setLimit(limit) {
_limit = limit;
return this;
}
setSeparator(separator) {
_separator = separator;
return this;
}
getLimit() {
return _limit;
}
getSeparator() {
return _separator;
}
getSize() {
return _size;
}
add(key, val) {
key = _getKey(key);
/**
* Memory management
*/
_isOverLimit = this.getSize() >= this.getLimit() && !_isOverLimit;
if (_isOverLimit) {
this.remove(this.keys()[0]);
}
if (!this.get(key)) {
_cache[key] = val;
_size++;
}
}
get(key) {
key = _getKey(key);
if (!_has(key)) {
return false;
}
return _cache[key];
}
update(key, newValue) {
key = _getKey(key);
if (_has(key)) {
_cache[key] = newValue;
return this;
}
throw new ReferenceError('No data found in cache for this query.');
}
remove(key) {
key = _getKey(key);
if (_has(key)) {
delete _cache[key];
_size--;
return this;
}
throw new ReferenceError('No data found in cache for this query.');
}
all() {
return _cache;
}
keys() {
return Object.keys(_cache);
}
clear() {
_cache = {};
_size = 0;
_isOverLimit = false;
}
}
const _has = (key) => {
key = _getKey(key);
return _cache.hasOwnProperty(key);
};
const _getKey = (keys) => {
if (_is(keys, 'string')) {
return keys.toUpperCase();
}
if (!_is(keys, 'array')) {
throw new TypeError('Key must be an Array or String type.');
}
return keys.join(_separator).replace(/\s/gi, _separator).toUpperCase();
};
const _is = (obj, expected) => {
let expectedLowerCase = expected.toLowerCase();
let expectedType = `[object ${expectedLowerCase}]`;
return Object.prototype.toString.call(obj).toLowerCase() === expectedType;
};
/**
* Add methods aliases
*/
JSMemcache.prototype.set = JSMemcache.prototype.add;
JSMemcache.prototype.replace = JSMemcache.prototype.update;
export default JSMemcache;