add MapIter2 for iterating over iter.Seq2 values
2 files changed, 33 insertions(+), 0 deletions(-)
changed files
M gomponents.go → gomponents.go
@@ -291,6 +291,19 @@ }, } } +// Map an iterator of pairs of values to an IterNode (which is just an [iter.Seq] of [Node]-s) +func MapIter2[K, V any](ts iter.Seq2[K, V], cb func(K, V) Node) IterNode { + return IterNode{ + func(yield func(Node) bool) { + for k, v := range ts { + if !yield(cb(k, v)) { + return + } + } + }, + } +} + type IterNode struct { iter.Seq[Node] }
M gomponents_test.go → gomponents_test.go
@@ -4,6 +4,7 @@ import ( "errors" "fmt" "io" + "maps" "os" "slices" "strings"@@ -318,6 +319,25 @@ return g.El("li", g.Text(value)) })) _ = e.Render(os.Stdout) // Output: <ul><li>party hat</li><li>super hat</li></ul> +} + +func TestMapIter2(t *testing.T) { + t.Run("maps a iter.Seq2 of items", func(t *testing.T) { + items := maps.All(map[string]string{"party": "hat", "super": "hat"}) + e := g.El("ul", g.MapIter2(items, func(key string, value string) g.Node { + return g.El("li", g.Textf("%v: %v", key, value)) + })) + assert.Equal(t, `<ul><li>party: hat</li><li>super: hat</li></ul>`, e) + }) +} + +func ExampleMapIter2() { + items := maps.All(map[string]string{"party": "hat", "super": "hat"}) + e := g.El("ul", g.MapIter2(items, func(key string, value string) g.Node { + return g.El("li", g.Textf("%v: %v", key, value)) + })) + _ = e.Render(os.Stdout) + // Output: <ul><li>party: hat</li><li>super: hat</li></ul> } func TestGroup(t *testing.T) {