forked from turbolinks/turbolinks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnapshot_cache.ts
54 lines (44 loc) · 1.16 KB
/
snapshot_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
46
47
48
49
50
51
52
53
54
import { Location } from "./location"
import { Snapshot } from "./snapshot"
export class SnapshotCache {
readonly keys: string[] = []
readonly snapshots: { [url: string]: Snapshot } = {}
readonly size: number
constructor(size: number) {
this.size = size
}
has(location: Location) {
return location.toCacheKey() in this.snapshots
}
get(location: Location): Snapshot | undefined {
if (this.has(location)) {
const snapshot = this.read(location)
this.touch(location)
return snapshot
}
}
put(location: Location, snapshot: Snapshot) {
this.write(location, snapshot)
this.touch(location)
return snapshot
}
// Private
read(location: Location) {
return this.snapshots[location.toCacheKey()]
}
write(location: Location, snapshot: Snapshot) {
this.snapshots[location.toCacheKey()] = snapshot
}
touch(location: Location) {
const key = location.toCacheKey()
const index = this.keys.indexOf(key)
if (index > -1) this.keys.splice(index, 1)
this.keys.unshift(key)
this.trim()
}
trim() {
for (const key of this.keys.splice(this.size)) {
delete this.snapshots[key]
}
}
}