-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
44 lines (43 loc) · 1.06 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
import throttle from 'lodash.throttle'
export default class TTLMap extends Map {
constructor(iterable = [], ttl = 60000, evictInterval = 10000, remove = function (value, key) { }) {
super()
this.ttl = ttl
this.evictInterval = evictInterval
this.deleteExpired = throttle(
() => {
this.ledger.forEach(
(value, key) => {
if (Date.now() > value) {
this.ledger.delete(key)
remove(super.get(key), key)
this.delete(key)
}
}
)
if (this.ledger.size)
this.deleteExpired()
},
this.evictInterval,
{
leading: false
}
)
this.ledger = new Map()
for (const [key, value] of iterable)
this.set(key, value)
}
set(key, value) {
this.ledger.set(key, Date.now() + this.ttl)
this.deleteExpired()
return super.set(key, value)
}
get(key) {
const value = super.get(key)
if (value) {
this.ledger.set(key, Date.now() + this.ttl)
this.deleteExpired()
}
return value
}
}