Add Last helper method (#6)
It is very common for FilterPath functions to operate on the last step
in a path. However, it is a hindrance to continually write:
if len(p) == 0 {
return false
}
return p[len(p)-1].Type() == ...
Instead, add a helper method Last that avoids the empty path check
and the indexing to the last element.
This allows users to simply write:
return p.Last().Type() == ...
This is more readable and writeable.
diff --git a/cmp/path.go b/cmp/path.go
index ae6af40..d760d8d 100644
--- a/cmp/path.go
+++ b/cmp/path.go
@@ -79,6 +79,15 @@
*pa = (*pa)[:len(*pa)-1]
}
+// Last returns the last PathStep in the Path.
+// If the path is empty, this returns a non-nil PathStep that reports a nil Type.
+func (pa Path) Last() PathStep {
+ if len(pa) > 0 {
+ return pa[len(pa)-1]
+ }
+ return pathStep{}
+}
+
// String returns the simplified path to a node.
// The simplified path only contains struct field accesses.
//
@@ -186,6 +195,9 @@
func (ps pathStep) Type() reflect.Type { return ps.typ }
func (ps pathStep) String() string {
+ if ps.typ == nil {
+ return "<nil>"
+ }
s := ps.typ.String()
if s == "" || strings.ContainsAny(s, "{}\n") {
return "root" // Type too simple or complex to print