-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
46 lines (36 loc) · 1008 Bytes
/
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
'use strict';
module.exports = TTLPool
var Dict = require('dict')
function TTLPool(ttl, cb) {
if (!(this instanceof TTLPool)) return new TTLPool(ttl, cb)
if (typeof ttl == 'function') {
cb = ttl
ttl = 0
}
this.ttl = ttl
this._cb = cb
this._dict = new Dict()
}
TTLPool.prototype.add = function(name, ttl) {
ttl = ttl || this.ttl
if (this._dict.has(name)) return
this._dict.set(name, setTimeout(this._expire.bind(this, name), ttl))
}
TTLPool.prototype._expire = function(name, explicit) {
this.remove(name)
var cb = this._cb
cb(name, explicit)
}
TTLPool.prototype.expire = function(name) {
this._expire(name, true)
}
TTLPool.prototype.remove = function(name) {
var timer = this._dict.get(name)
if (this._dict.delete(name)) clearTimeout(timer)
}
TTLPool.prototype.ping = function(name, ttl) {
ttl = ttl || this.ttl
if (!this._dict.has(name)) return
clearTimeout(this._dict.get(name))
this._dict.set(name, setTimeout(this._expire.bind(this, name), ttl))
}