From 65c0ed3569fecab319a598ba99d52a9c87f0fa7d Mon Sep 17 00:00:00 2001 From: Amelia <77553571+Fesaa@users.noreply.github.com> Date: Thu, 22 Feb 2024 17:12:50 +0100 Subject: [PATCH] Impl PuerkitoBio/goquery#466 --- go.mod | 2 +- iteration.go | 9 +++++++++ iteration_test.go | 19 +++++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 7ab501a..b14b27a 100644 --- a/go.mod +++ b/go.mod @@ -5,4 +5,4 @@ require ( golang.org/x/net v0.17.0 ) -go 1.13 +go 1.18 diff --git a/iteration.go b/iteration.go index e246f2e..64dc5a2 100644 --- a/iteration.go +++ b/iteration.go @@ -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 +} \ No newline at end of file diff --git a/iteration_test.go b/iteration_test.go index 9b6aafb..dd6fefa 100644 --- a/iteration_test.go +++ b/iteration_test.go @@ -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)) + } +}