Skip to content

Commit b09f5a8

Browse files
author
ntwigg
committed
Added TreeQuery.root().
1 parent abcb2d2 commit b09f5a8

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

src/com/diffplug/common/base/TreeQuery.java

+11
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,17 @@
2828

2929
/** Queries against {@link TreeDef} trees, e.g. lowest common ancestor, list of parents, etc. */
3030
public class TreeQuery {
31+
/** Returns the root of the given tree. */
32+
public static <T> T root(TreeDef.Parented<T> treeDef, T node) {
33+
T lastParent;
34+
T parent = node;
35+
do {
36+
lastParent = parent;
37+
parent = treeDef.parentOf(lastParent);
38+
} while (parent != null);
39+
return lastParent;
40+
}
41+
3142
/** Creates a mutable list whose first element is {@code node}, and last element is its root parent. */
3243
public static <T> List<T> toRoot(TreeDef.Parented<T> treeDef, T node) {
3344
List<T> list = new ArrayList<>();

test/com/diffplug/common/base/TreeQueryTest.java

+7
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,13 @@
1919
import org.junit.Test;
2020

2121
public class TreeQueryTest {
22+
@Test
23+
public void testToRoot() {
24+
Assert.assertEquals(root, TreeQuery.root(TreeNode.treeDef(), root));
25+
Assert.assertEquals(root, TreeQuery.root(TreeNode.treeDef(), root.findByContent("src")));
26+
Assert.assertEquals(root, TreeQuery.root(TreeNode.treeDef(), root.findByContent("Array.java")));
27+
}
28+
2229
@Test
2330
public void testLowestCommonAncestor() {
2431
// test the trivial case

0 commit comments

Comments
 (0)