This repository has been archived by the owner on Oct 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
135 lines (106 loc) · 2.49 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
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var LinkedList = require('./lib/linkedlist');
var linkedlist = new LinkedList();
function Fleeting(opts) {
opts = (Object.prototype.toString.call(opts) === '[object Object]') ? opts : {};
this._max = (opts.max > 0) ? parseInt(opts.max) : Infinity;
this._ttl = (opts.ttl > 0) ? parseInt(opts.ttl) : false;
this._cache = {};
Object.defineProperties(this, {
'_length': {
get: function() {
return linkedlist._length;
}
},
'_linkedlist': {
get: function() {
return linkedlist;
}
}
});
}
util.inherits(Fleeting, EventEmitter);
Fleeting.prototype._Node = function(k, v) {
var node = {
data: {
k: k,
v: v
},
next: null,
prev: null
};
var ttl = this._ttl;
if (ttl > 0) {
node.exp = Date.now() + ttl;
}
node.constructor = this._Node;
return node;
};
function nodeByKey(k, node) {
return node.data.k === k;
}
function stale(node) {
return node.exp < Date.now();
}
Fleeting.prototype.purge = function(k) {
this._cache = {};
linkedlist = new LinkedList();
};
Fleeting.prototype.peek = function(k) {
return this._cache[k];
};
Fleeting.prototype.has = function(k) {
return this._cache[k] === undefined ? false : true;
};
Fleeting.prototype.get = function(k) {
var cachedNode = this._cache[k];
if (cachedNode !== undefined) {
setImmediate(function() {
var node = linkedlist.get(nodeByKey.bind(null, k));
if (!node) {
return;
}
if (stale(node)) {
this.del(node);
this.emit('evicted', {
k: node.data.k,
v: node.data.v,
stale: true
});
} else {
linkedlist.attachHead(node);
}
}.bind(this));
}
return cachedNode;
};
Fleeting.prototype.set = function(k, v) {
var node = this._Node(k, v);
if (linkedlist._length >= this._max) {
var eviction = linkedlist.get(null, true);
if (eviction) {
this.del(eviction);
this.emit('evicted', {
k: eviction.data.k,
v: eviction.data.v,
stale: false
});
}
}
this._cache[k] = v;
linkedlist.prepend(node);
return node.data.v;
};
Fleeting.prototype.del = function(node) {
if (node.constructor !== this._Node) {
node = linkedlist.get(nodeByKey.bind(null, node));
}
if (!node) {
return;
}
linkedlist.unlink(node);
delete this._cache[node.data.k];
return node.data.v;
};
module.exports = Fleeting;