Skip to content

Commit

Permalink
Merge pull request #3 from lestrrat-go/fix-ancestors
Browse files Browse the repository at this point in the history
Fix Ancestors()
  • Loading branch information
lestrrat authored Oct 13, 2024
2 parents ac25977 + 2348ac8 commit 5e6058b
Showing 1 changed file with 24 additions and 8 deletions.
32 changes: 24 additions & 8 deletions trie.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,18 @@ type Node[K cmp.Ordered, V any] interface {
// Parent returns the parent of this node
Parent() Node[K, V]

// Ancestors returns a sequence of ancestors of this node
// Ancestors returns a sequence of ancestors of this node.
// The first element is the root element, progressing all the way
// up to the parent of this node.
Ancestors() iter.Seq[Node[K, V]]
}

// New creates a new Trie object.
func New[L any, K cmp.Ordered, V any](tokenizer Tokenizer[L, K]) *Trie[L, K, V] {
node := newNode[K, V]()
node.isRoot = true
return &Trie[L, K, V]{
root: newNode[K, V](),
root: node,
tokenizer: tokenizer,
}
}
Expand Down Expand Up @@ -220,7 +224,7 @@ func put[K cmp.Ordered, V any](root Node[K, V], tokens []K, value V) {
if cur == nil {
newRoot = newNode
} else {
cur.children = append(cur.children, newNode)
cur.AddChild(newNode)
}
cur = newNode
}
Expand All @@ -234,6 +238,7 @@ type node[K cmp.Ordered, V any] struct {
mu sync.RWMutex
key K
value V
isRoot bool
children []*node[K, V]
parent *node[K, V]
}
Expand All @@ -255,13 +260,24 @@ func (n *node[K, V]) Parent() Node[K, V] {
}

func (n *node[K, V]) Ancestors() iter.Seq[Node[K, V]] {
var ancestors []*node[K, V]
for {
n = n.parent
if n == nil {
break
}
ancestors = append(ancestors, n)
}

return func(yield func(Node[K, V]) bool) {
cur := n.parent
for cur != nil {
if !yield(cur) {
break
for len(ancestors) > 0 {
cur := ancestors[len(ancestors)-1]
if cur != nil && !cur.isRoot {
if !yield(cur) {
break
}
}
cur = cur.parent
ancestors = ancestors[:len(ancestors)-1]
}
}
}
Expand Down

0 comments on commit 5e6058b

Please sign in to comment.