iter.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2024 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //go:build go1.23
  5. package html
  6. import "iter"
  7. // Ancestors returns an iterator over the ancestors of n, starting with n.Parent.
  8. //
  9. // Mutating a Node or its parents while iterating may have unexpected results.
  10. func (n *Node) Ancestors() iter.Seq[*Node] {
  11. _ = n.Parent // eager nil check
  12. return func(yield func(*Node) bool) {
  13. for p := n.Parent; p != nil && yield(p); p = p.Parent {
  14. }
  15. }
  16. }
  17. // ChildNodes returns an iterator over the immediate children of n,
  18. // starting with n.FirstChild.
  19. //
  20. // Mutating a Node or its children while iterating may have unexpected results.
  21. func (n *Node) ChildNodes() iter.Seq[*Node] {
  22. _ = n.FirstChild // eager nil check
  23. return func(yield func(*Node) bool) {
  24. for c := n.FirstChild; c != nil && yield(c); c = c.NextSibling {
  25. }
  26. }
  27. }
  28. // Descendants returns an iterator over all nodes recursively beneath
  29. // n, excluding n itself. Nodes are visited in depth-first preorder.
  30. //
  31. // Mutating a Node or its descendants while iterating may have unexpected results.
  32. func (n *Node) Descendants() iter.Seq[*Node] {
  33. _ = n.FirstChild // eager nil check
  34. return func(yield func(*Node) bool) {
  35. n.descendants(yield)
  36. }
  37. }
  38. func (n *Node) descendants(yield func(*Node) bool) bool {
  39. for c := range n.ChildNodes() {
  40. if !yield(c) || !c.descendants(yield) {
  41. return false
  42. }
  43. }
  44. return true
  45. }