-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTraverser.js
113 lines (90 loc) · 2.09 KB
/
Traverser.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
import toNT from '@rdfjs/to-ntriples'
class Visisted {
constructor () {
this.quadLevel = new Map()
}
add (quad, level) {
this.quadLevel.set(toNT(quad), level)
}
has (quad, level) {
const seenAt = this.quadLevel.get(toNT(quad))
if (seenAt === undefined) {
return false
}
return seenAt <= level
}
}
function forEach ({ backward, callback, dataset, filter, forward, term, visited = new Visisted() }) {
const next = (term, level) => {
const checkMatches = matches => {
for (const quad of matches) {
if (visited.has(quad, level)) {
continue
}
visited.add(quad, level)
const args = { dataset, level, quad }
if (filter(args)) {
callback(args)
if (forward) {
next(quad.object, level + 1)
}
if (backward) {
next(quad.subject, level + 1)
}
}
}
}
if (forward) {
checkMatches(dataset.match(term))
}
if (backward) {
checkMatches(dataset.match(null, null, term))
}
}
next(term, 0)
}
class Traverser {
constructor (filter, { backward = false, factory, forward = true }) {
this.backward = backward
this.factory = factory
this.filter = filter
this.forward = forward
}
forEach ({ term, dataset }, callback) {
forEach({
backward: this.backward,
callback,
dataset,
filter: this.filter,
forward: this.forward,
term
})
}
match ({ term, dataset }) {
const result = this.factory.dataset()
forEach({
backward: this.backward,
callback: ({ quad }) => result.add(quad),
dataset,
filter: this.filter,
forward: this.forward,
term
})
return result
}
reduce ({ term, dataset }, callback, initialValue) {
let result = initialValue
forEach({
backward: this.backward,
callback: args => {
result = callback(args, result)
},
dataset,
filter: this.filter,
forward: this.forward,
term
})
return result
}
}
export default Traverser