From 8ddd8c6655cdf1aca7c32f5f337e53df3137dd5a Mon Sep 17 00:00:00 2001 From: Martin Angers Date: Sat, 1 Sep 2012 10:55:01 -0400 Subject: [PATCH] finalize iterators, with tests and comments. --- doc.go | 2 +- iteration.go | 3 ++- iteration_test.go | 20 ++++++++++++++++++++ 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/doc.go b/doc.go index 7fe9ad4..7e0f67c 100644 --- a/doc.go +++ b/doc.go @@ -102,7 +102,7 @@ package goquery // DONE query.go : Reflect (query) node: Is(), Contains(), HasClass() // property.go : Inspect node: Contents(), Html(), Text(), Attr(), ** Does it make sense in a static HTML tree? Val()**, Length(), Size() // traversal.go : Traversal: Find(), Children(), Parents...(), Next...(), Prev...(), Closest(), Siblings() -// iteration.go : Iteration: Each(), Map() +// DONE iteration.go : Iteration: Each(), Map() // type.go : Selection and Document // TODO : Benchmarks diff --git a/iteration.go b/iteration.go index 47b037d..17a5ee7 100644 --- a/iteration.go +++ b/iteration.go @@ -1,6 +1,7 @@ package goquery -// Returns this (same Selection object) +// Each() iterates over a Selection object, executing a function for each +// matched element. func (this *Selection) Each(f func(int, *Selection)) *Selection { for i, n := range this.Nodes { f(i, newSingleSelection(n, this.document)) diff --git a/iteration_test.go b/iteration_test.go index f1753e4..b5993cd 100644 --- a/iteration_test.go +++ b/iteration_test.go @@ -1,6 +1,7 @@ package goquery import ( + "exp/html" "testing" ) @@ -19,3 +20,22 @@ func TestEach(t *testing.T) { t.Errorf("Expected 6 matching nodes, found %v.", len(sel.Nodes)) } } + +func TestMap(t *testing.T) { + sel := Doc().Find(".pvk-content") + vals := sel.Map(func(i int, s *Selection) string { + n := s.Get(0) + if n.Type == html.ElementNode { + return n.Data + } + return "" + }) + for _, v := range vals { + if v != "div" { + 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)) + } +}