-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtree.ts
More file actions
43 lines (40 loc) · 1.3 KB
/
tree.ts
File metadata and controls
43 lines (40 loc) · 1.3 KB
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
import type { box } from '../BoundingBox';
export type SpatialTreeInterface<Tree, Content, V extends ReadonlyArray<number>> = {
bounds: (t: Tree) => box<V>;
content: (t: Tree) => Content;
children: (t: Tree) => ReadonlyArray<Tree>;
};
export function visitBFS<Tree>(
tree: Tree,
children: (t: Tree) => ReadonlyArray<Tree>,
visitor: (tree: Tree) => void,
traversalPredicate?: (t: Tree) => boolean,
): void {
const frontier: Tree[] = [tree];
while (frontier.length > 0) {
const cur = frontier.shift()!;
visitor(cur);
for (const c of children(cur)) {
if (traversalPredicate?.(c) ?? true) {
// predicate?.(c) is true false or undefined. if its undefined, we coerce it to true with ??
// because we want to always traverse children if the predicate isn't given
frontier.push(c);
}
}
}
}
export function visitBFSMaybe<Tree>(
tree: Tree,
children: (t: Tree) => ReadonlyArray<Tree>,
visitor: (tree: Tree) => boolean,
): void {
const frontier: Tree[] = [tree];
while (frontier.length > 0) {
const cur = frontier.shift()!;
if (visitor(cur)) {
for (const c of children(cur)) {
frontier.push(c);
}
}
}
}