Skip to content

Commit 65c0ed3

Browse files
committed
Impl #466
1 parent b6c7644 commit 65c0ed3

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@ require (
55
golang.org/x/net v0.17.0
66
)
77

8-
go 1.13
8+
go 1.18

iteration.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,12 @@ func (s *Selection) Map(f func(int, *Selection) string) (result []string) {
3737

3838
return result
3939
}
40+
41+
// Generic version of Selection.Map, allowing any type to be returned.
42+
func Map[E any](s *Selection, f func(int, *Selection) E) (result []E) {
43+
for i, n := range s.Nodes {
44+
result = append(result, f(i, newSingleSelection(n, s.document)))
45+
}
46+
47+
return result
48+
}

iteration_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,3 +86,22 @@ func TestForRange(t *testing.T) {
8686
t.Errorf("expected initial selection to still have length %d, got %d", initLen, sel.Length())
8787
}
8888
}
89+
90+
func TestGenericMap(t *testing.T) {
91+
sel := Doc().Find(".pvk-content")
92+
vals := Map(sel, func(i int, s *Selection) *html.NodeType {
93+
n := s.Get(0)
94+
if n.Type == html.ElementNode {
95+
return &n.Type
96+
}
97+
return nil
98+
})
99+
for _, v := range vals {
100+
if v == nil || *v != html.ElementNode {
101+
t.Error("Expected Map array result to be all 'div's.")
102+
}
103+
}
104+
if len(vals) != 3 {
105+
t.Errorf("Expected Map array result to have a length of 3, found %v.", len(vals))
106+
}
107+
}

0 commit comments

Comments
 (0)