-
Notifications
You must be signed in to change notification settings - Fork 27
/
index.js
51 lines (40 loc) · 1.05 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
module.exports = function (max) {
if (!max) throw Error('hashlru must have a max value, of type number, greater than 0')
var size = 0, cache = Object.create(null), _cache = Object.create(null)
function update (key, value) {
cache[key] = value
size ++
if(size >= max) {
size = 0
_cache = cache
cache = Object.create(null)
}
}
return {
has: function (key) {
return cache[key] !== undefined || _cache[key] !== undefined
},
remove: function (key) {
if(cache[key] !== undefined)
cache[key] = undefined
if(_cache[key] !== undefined)
_cache[key] = undefined
},
get: function (key) {
var v = cache[key]
if(v !== undefined) return v
if((v = _cache[key]) !== undefined) {
update(key, v)
return v
}
},
set: function (key, value) {
if(cache[key] !== undefined) cache[key] = value
else update(key, value)
},
clear: function () {
cache = Object.create(null)
_cache = Object.create(null)
}
}
}