Skip to content

Commit

Permalink
Add Path.Index helper method
Browse files Browse the repository at this point in the history
An analysis of user code shows that Path.Last was not sufficient and
that what users really wanted was an easy want to do negative indexing
without needing to constantly check for out-of-bounds.

Thus, add a generic Index method that does not panic on out-of-bounds
accesses and supports negative indexing.
  • Loading branch information
dsnet committed Dec 1, 2017
1 parent 3f298f3 commit c02d683
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions cmp/path.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,21 @@ func (pa *Path) pop() {
// 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 pa.Index(-1)
}

// Index returns the ith step in the Path and supports negative indexing.
// A negative index starts counting from the tail of the Path such that -1
// refers to the last step, -2 refers to the second-to-last step, and so on.
// If index is invalid, this returns a non-nil PathStep that reports a nil Type.
func (pa Path) Index(i int) PathStep {
if i < 0 {
i = len(pa) + i
}
if i < 0 || i >= len(pa) {
return pathStep{}
}
return pathStep{}
return pa[i]
}

// String returns the simplified path to a node.
Expand Down

0 comments on commit c02d683

Please sign in to comment.