forked from openstf/stf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathttlset.js
124 lines (94 loc) · 2.12 KB
/
ttlset.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
var util = require('util')
var EventEmitter = require('eventemitter3')
function TtlItem(value) {
this.next = null
this.prev = null
this.time = null
this.value = value
}
function TtlSet(ttl) {
EventEmitter.call(this)
this.head = null
this.tail = null
this.mapping = Object.create(null)
this.ttl = ttl
this.timer = null
}
util.inherits(TtlSet, EventEmitter)
TtlSet.SILENT = 1
TtlSet.prototype.bump = function(value, time, flags) {
var item = this._remove(this.mapping[value]) || this._create(value, flags)
item.time = time || Date.now()
item.prev = this.tail
this.tail = item
if (item.prev) {
item.prev.next = item
}
else {
this.head = item
this._scheduleCheck()
}
}
TtlSet.prototype.drop = function(value, flags) {
this._drop(this.mapping[value], flags)
}
TtlSet.prototype.stop = function() {
clearTimeout(this.timer)
}
TtlSet.prototype._scheduleCheck = function() {
clearTimeout(this.timer)
if (this.head) {
var delay = Math.max(0, this.ttl - (Date.now() - this.head.time))
this.timer = setTimeout(this._check.bind(this), delay)
}
}
TtlSet.prototype._check = function() {
var now = Date.now()
var item
while ((item = this.head)) {
if (now - item.time > this.ttl) {
this._drop(item, 0)
}
else {
break
}
}
this._scheduleCheck()
}
TtlSet.prototype._create = function(value, flags) {
var item = new TtlItem(value)
this.mapping[value] = item
if ((flags & TtlSet.SILENT) !== TtlSet.SILENT) {
this.emit('insert', value)
}
return item
}
TtlSet.prototype._drop = function(item, flags) {
if (item) {
this._remove(item)
delete this.mapping[item.value]
if ((flags & TtlSet.SILENT) !== TtlSet.SILENT) {
this.emit('drop', item.value)
}
}
}
TtlSet.prototype._remove = function(item) {
if (!item) {
return null
}
if (item.prev) {
item.prev.next = item.next
}
if (item.next) {
item.next.prev = item.prev
}
if (item === this.head) {
this.head = item.next
}
if (item === this.tail) {
this.tail = item.prev
}
item.next = item.prev = null
return item
}
module.exports = TtlSet