add Path.parent() and Path.last() methods

Neither is very efficient, but we'll live.
This commit is contained in:
Havoc Pennington 2011-11-17 12:08:27 -05:00
parent d8e54099e9
commit 88e81d7c67
2 changed files with 46 additions and 0 deletions

View File

@ -53,10 +53,43 @@ final class Path {
return first;
}
/**
*
* @return path minus the first element or null if no more elements
*/
Path remainder() {
return remainder;
}
/**
*
* @return path minus the last element or null if we have just one element
*/
Path parent() {
if (remainder == null)
return null;
PathBuilder pb = new PathBuilder();
Path p = this;
while (p.remainder != null) {
pb.appendKey(p.first);
p = p.remainder;
}
return pb.result();
}
/**
*
* @return last element in the path
*/
String last() {
Path p = this;
while (p.remainder != null) {
p = p.remainder;
}
return p.first;
}
Path prepend(Path toPrepend) {
PathBuilder pb = new PathBuilder();
pb.appendPath(toPrepend);

View File

@ -64,6 +64,19 @@ class PathTest extends TestUtils {
assertEquals(2, path("foo", "bar").length())
}
@Test
def pathParent() {
assertNull(path("a").parent())
assertEquals(path("a"), path("a", "b").parent())
assertEquals(path("a", "b"), path("a", "b", "c").parent())
}
@Test
def pathLast() {
assertEquals("a", path("a").last())
assertEquals("b", path("a", "b").last())
}
@Test
def pathsAreInvalid() {
// this test is just of the Path.newPath() wrapper, the extensive