Skip to content

Commit

Permalink
add Node.Parents
Browse files Browse the repository at this point in the history
  • Loading branch information
earthboundkid committed Jun 22, 2024
1 parent 74b75cf commit 13a4d2c
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module golang.org/x/net

go 1.18
go 1.22

require (
golang.org/x/crypto v0.24.0
Expand Down
11 changes: 11 additions & 0 deletions html/iter.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,14 @@ func (n *Node) All() iter.Seq[*Node] {
n.all(yield)
}
}

// Parents returns an sequence yielding the node and its parents.
func (n *Node) Parents() iter.Seq[*Node] {
return func(yield func(*Node) bool) {
for p := n; p != nil; p = p.Parent {
if !yield(p) {
return
}
}
}
}
33 changes: 33 additions & 0 deletions html/iter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,36 @@ func TestNode_All(t *testing.T) {
}
}
}

func TestNode_Parents(t *testing.T) {
testParents(t, nil, 0)
for size := range 100 {
n := buildChain(size)
testParents(t, n, size+1)
}
}

func testParents(t *testing.T, n *Node, wantSize int) {
nParents := 0
for _ = range n.Parents() {
nParents++
}
if nParents != wantSize {
t.Errorf("unexpected number of Parents; want %d got: %d", wantSize, nParents)
}
}

func buildChain(size int) *Node {
descendent := &Node{
Type: ElementNode,
}
current := descendent
for range size {
parent := &Node{
Type: ElementNode,
}
parent.AppendChild(current)
current = parent
}
return descendent
}

0 comments on commit 13a4d2c

Please sign in to comment.