forked from Kong/swrv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.ts
45 lines (37 loc) · 795 Bytes
/
cache.ts
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
interface ICacheItem {
data: any,
createdAt: number
}
export default class SWRCache {
private ttl: number
private items: Map<string, ICacheItem>
constructor (ttl = 0) {
this.items = new Map()
this.ttl = ttl
}
get (k: string, ttl: number): any {
this.shift(ttl)
return this.items.get(k) && this.items.get(k).data
}
set (k: string, v: any) {
const item: ICacheItem = {
data: v,
createdAt: Date.now()
}
this.items.set(k, item)
}
private shift (ttl: number) {
const timeToLive = ttl || this.ttl
if (!timeToLive) {
return
}
this.items.forEach((v, k) => {
if (v.createdAt < Date.now() - timeToLive) {
this.items.delete(k)
}
})
}
delete (k: string) {
this.items.delete(k)
}
}