/
MapExpire.js
76 lines (66 loc) · 1.75 KB
/
MapExpire.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
const EventEmitter = require('events')
class Entity {
constructor(key, value, duration, map){
this.key = key
this.value = value
this.expire = duration && (Date.now() + duration)
this.timer = duration && setTimeout(() => map.delete(key), duration)
}
update(value, duration, map){
this.value = value
if (duration) {
if (this.timer) clearTimeout(this.timer)
this.expire = duration && (Date.now() + duration)
this.timer = setTimeout(() => map.delete(this.key), duration)
}
}
}
class MapExpire extends Map {
constructor(values, options){
super()
this.events = new EventEmitter()
this.capacity = options && options.capacity
this.duration = options && options.duration
if (values) values.forEach(item => this.set(...item))
}
set(key, value, duration){
const entity = super.get(key)
if (entity) {
entity.update(value, duration, this)
this.events.emit('update', key, value)
}
else {
super.set(key, new Entity(key, value, duration || this.duration, this))
this.events.emit('set', key, value)
}
this.clean()
}
get(key){
const entity = super.get(key)
return entity && entity.value
}
delete(key){
const superKey = super.get(key)
if (superKey) this.events.emit('delete', key, superKey.value)
super.delete(key)
}
clear(){
for (let key of this.keys()) {
this.delete(key)
}
super.clear()
}
clean(){
const {size, capacity} = this
if (!capacity || size <= capacity) return
var keys = this.keys()
while (this.size > this.capacity){
var key = keys.next().value
this.delete(key)
}
}
on(event, callback){
this.events.on(event, callback)
}
}
module.exports = MapExpire