rss-tools/vendor/github.com/PuerkitoBio/goquery/iteration.go (view raw)
| 1 | package goquery |
| 2 | |
| 3 | import "iter" |
| 4 | |
| 5 | // Each iterates over a Selection object, executing a function for each |
| 6 | // matched element. It returns the current Selection object. The function |
| 7 | // f is called for each element in the selection with the index of the |
| 8 | // element in that selection starting at 0, and a *Selection that contains |
| 9 | // only that element. |
| 10 | func (s *Selection) Each(f func(int, *Selection)) *Selection { |
| 11 | for i, n := range s.Nodes { |
| 12 | f(i, newSingleSelection(n, s.document)) |
| 13 | } |
| 14 | return s |
| 15 | } |
| 16 | |
| 17 | // EachIter returns an iterator that yields the Selection object in order. |
| 18 | // The implementation is similar to Each, but it returns an iterator instead. |
| 19 | func (s *Selection) EachIter() iter.Seq2[int, *Selection] { |
| 20 | return func(yield func(int, *Selection) bool) { |
| 21 | for i, n := range s.Nodes { |
| 22 | if !yield(i, newSingleSelection(n, s.document)) { |
| 23 | return |
| 24 | } |
| 25 | } |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | // EachWithBreak iterates over a Selection object, executing a function for each |
| 30 | // matched element. It is identical to Each except that it is possible to break |
| 31 | // out of the loop by returning false in the callback function. It returns the |
| 32 | // current Selection object. |
| 33 | func (s *Selection) EachWithBreak(f func(int, *Selection) bool) *Selection { |
| 34 | for i, n := range s.Nodes { |
| 35 | if !f(i, newSingleSelection(n, s.document)) { |
| 36 | return s |
| 37 | } |
| 38 | } |
| 39 | return s |
| 40 | } |
| 41 | |
| 42 | // Map passes each element in the current matched set through a function, |
| 43 | // producing a slice of string holding the returned values. The function |
| 44 | // f is called for each element in the selection with the index of the |
| 45 | // element in that selection starting at 0, and a *Selection that contains |
| 46 | // only that element. |
| 47 | func (s *Selection) Map(f func(int, *Selection) string) (result []string) { |
| 48 | return Map(s, f) |
| 49 | } |
| 50 | |
| 51 | // Map is the generic version of Selection.Map, allowing any type to be |
| 52 | // returned. |
| 53 | func Map[E any](s *Selection, f func(int, *Selection) E) (result []E) { |
| 54 | result = make([]E, len(s.Nodes)) |
| 55 | |
| 56 | for i, n := range s.Nodes { |
| 57 | result[i] = f(i, newSingleSelection(n, s.document)) |
| 58 | } |
| 59 | |
| 60 | return result |
| 61 | } |