Skip to content

Commit

Permalink
Impl #466
Browse files Browse the repository at this point in the history
  • Loading branch information
Fesaa committed Feb 22, 2024
1 parent b6c7644 commit 65c0ed3
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ require (
golang.org/x/net v0.17.0
)

go 1.13
go 1.18
9 changes: 9 additions & 0 deletions iteration.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
19 changes: 19 additions & 0 deletions iteration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
}

0 comments on commit 65c0ed3

Please sign in to comment.