diff options
author | Alan Pearce | 2025-03-19 01:26:01 +0100 |
---|---|---|
committer | Alan Pearce | 2025-03-19 11:51:04 +0100 |
commit | 6aea6d0965f9030d598eb87f5bfca36b638035f6 (patch) | |
tree | 89416fb5083b41e9b273a30f8200a806dccae54f | |
parent | 7ae7b677396aef6604a8700910ca49786c69c763 (diff) | |
download | gomponents-6aea6d0965f9030d598eb87f5bfca36b638035f6.tar.lz gomponents-6aea6d0965f9030d598eb87f5bfca36b638035f6.tar.zst gomponents-6aea6d0965f9030d598eb87f5bfca36b638035f6.zip |
add MapWithIndex and MapMap helpers
-rw-r--r-- | gomponents.go | 20 |
1 files changed, 20 insertions, 0 deletions
diff --git a/gomponents.go b/gomponents.go index ad9c2cd..37267d4 100644 --- a/gomponents.go +++ b/gomponents.go @@ -257,6 +257,26 @@ func Map[T any](ts []T, cb func(T) Node) Group { return nodes } +// Map a slice of anything to a [Group] (which is just a slice of [Node]-s). +func MapWithIndex[T any](ts []T, cb func(int, T) Node) Group { + nodes := make([]Node, 0, len(ts)) + for k, t := range ts { + nodes = append(nodes, cb(k, t)) + } + + return nodes +} + +// Map a map of anything to a [Group] (which is just a slice of [Node]-s). +func MapMap[K comparable, T any](ts map[K]T, cb func(K, T) Node) Group { + nodes := make([]Node, 0, len(ts)) + for k, t := range ts { + nodes = append(nodes, cb(k, t)) + } + + return nodes +} + // 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. |