diff options
author | Alan Pearce | 2025-03-21 21:52:31 +0100 |
---|---|---|
committer | Alan Pearce | 2025-03-21 21:52:31 +0100 |
commit | 85fff9ebf5a3177d8c4e48d7314e402c0be27cee (patch) | |
tree | 3f5713c898622585d2f75d919fd2cd3a329654a1 /gomponents.go | |
parent | 7ada5cf0a0ac21780e8ef5abd4be308446fa3110 (diff) | |
download | gomponents-1.4.0.tar.lz gomponents-1.4.0.tar.zst gomponents-1.4.0.zip |
Add MapIter to map over iterators v1.4.0
Diffstat (limited to 'gomponents.go')
-rw-r--r-- | gomponents.go | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/gomponents.go b/gomponents.go index 4867152..1848291 100644 --- a/gomponents.go +++ b/gomponents.go @@ -22,6 +22,7 @@ import ( "fmt" "html/template" "io" + "iter" "strings" ) @@ -277,6 +278,33 @@ func MapMap[K comparable, T any](ts map[K]T, cb func(K, T) Node) Group { return nodes } +// Map an iterator of anything to an IterNode (which is just an [iter.Seq] of [Node]-s) +func MapIter[T any](ts iter.Seq[T], cb func(T) Node) IterNode { + return IterNode{ + func(yield func(Node) bool) { + for t := range ts { + if !yield(cb(t)) { + return + } + } + }, + } +} + +type IterNode struct { + iter.Seq[Node] +} + +func (it IterNode) Render(w io.Writer) error { + for node := range it.Seq { + if err := node.Render(w); err != nil { + return err + } + } + + return nil +} + // Group a slice of [Node]-s into one Node, while still being usable like a regular slice of [Node]-s. // A [Group] can render directly, but if any of the direct children are [AttributeType], they will be ignored, // to not produce invalid HTML. |