mirror of
https://github.com/PuerkitoBio/goquery
synced 2025-12-24 12:38:00 +08:00
Merge pull request #467 from Fesaa/feature/generics
Add a generic form of Selection.Map
This commit is contained in:
@@ -37,3 +37,12 @@ func (s *Selection) Map(f func(int, *Selection) string) (result []string) {
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// Generic version of Selection.Map, allowing any type to be returned.
|
||||
func Map[E any](s *Selection, f func(int, *Selection) E) (result []E) {
|
||||
for i, n := range s.Nodes {
|
||||
result = append(result, f(i, newSingleSelection(n, s.document)))
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -86,3 +86,22 @@ func TestForRange(t *testing.T) {
|
||||
t.Errorf("expected initial selection to still have length %d, got %d", initLen, sel.Length())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenericMap(t *testing.T) {
|
||||
sel := Doc().Find(".pvk-content")
|
||||
vals := Map(sel, func(i int, s *Selection) *html.NodeType {
|
||||
n := s.Get(0)
|
||||
if n.Type == html.ElementNode {
|
||||
return &n.Type
|
||||
}
|
||||
return nil
|
||||
})
|
||||
for _, v := range vals {
|
||||
if v == nil || *v != html.ElementNode {
|
||||
t.Error("Expected Map array result to be all 'div's.")
|
||||
}
|
||||
}
|
||||
if len(vals) != 3 {
|
||||
t.Errorf("Expected Map array result to have a length of 3, found %v.", len(vals))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user