@@ -458,7 +458,7 @@ func (t *Tree) WalkPrefix(prefix string, fn WalkFn) {
458458 n := t .root
459459 search := prefix
460460 for {
461- // Check for key exhaution
461+ // Check for key exhaustion
462462 if len (search ) == 0 {
463463 recursiveWalk (n , fn )
464464 return
@@ -467,22 +467,20 @@ func (t *Tree) WalkPrefix(prefix string, fn WalkFn) {
467467 // Look for an edge
468468 n = n .getEdge (search [0 ])
469469 if n == nil {
470- break
470+ return
471471 }
472472
473473 // Consume the search prefix
474474 if strings .HasPrefix (search , n .prefix ) {
475475 search = search [len (n .prefix ):]
476-
477- } else if strings .HasPrefix (n .prefix , search ) {
476+ continue
477+ }
478+ if strings .HasPrefix (n .prefix , search ) {
478479 // Child may be under our search prefix
479480 recursiveWalk (n , fn )
480- return
481- } else {
482- break
483481 }
482+ return
484483 }
485-
486484}
487485
488486// WalkPath is used to walk the tree, but only visiting nodes
@@ -527,10 +525,27 @@ func recursiveWalk(n *node, fn WalkFn) bool {
527525 }
528526
529527 // Recurse on the children
530- for _ , e := range n .edges {
528+ i := 0
529+ k := len (n .edges ) // keeps track of number of edges in previous iteration
530+ for i < k {
531+ e := n .edges [i ]
531532 if recursiveWalk (e .node , fn ) {
532533 return true
533534 }
535+ // It is a possibility that the WalkFn modified the node we are
536+ // iterating on. If there are no more edges, mergeChild happened,
537+ // so the last edge became the current node n, on which we'll
538+ // iterate one last time.
539+ if len (n .edges ) == 0 {
540+ return recursiveWalk (n , fn )
541+ }
542+ // If there are now less edges than in the previous iteration,
543+ // then do not increment the loop index, since the current index
544+ // points to a new edge. Otherwise, get to the next index.
545+ if len (n .edges ) >= k {
546+ i ++
547+ }
548+ k = len (n .edges )
534549 }
535550 return false
536551}
0 commit comments