From 15e4d83ab998cb86397928e71145de7566ee2a84 Mon Sep 17 00:00:00 2001 From: Timon Ringwald Date: Wed, 9 Mar 2022 14:55:11 +0100 Subject: [PATCH] ToMap refactored --- to.go | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/to.go b/to.go index d27dff7..f4a65ca 100644 --- a/to.go +++ b/to.go @@ -30,23 +30,18 @@ func ToList[T any](ch <-chan T) *list.List { } // ToMap returns a map containing all values read from ch. -// The map keys are determined by f -func ToMap[K comparable, V any](ch <-chan V, f func(V) K) map[K]V { +// The map key-value pairs are determined by f +func ToMap[T any, K comparable, V any](ch <-chan T, f func(T) (K, V)) map[K]V { m := map[K]V{} - Each(ch, func(value V) { m[f(value)] = value }) - return m -} - -// ToKeyMap returns a map containing all values read from ch as keys. -// The map values are determined by f -func ToKeyMap[K comparable, V any](ch <-chan K, f func(K) V) map[K]V { - m := map[K]V{} - Each(ch, func(key K) { m[key] = f(key) }) + Each(ch, func(value T) { + k, v := f(value) + m[k] = v + }) return m } // ToStructMap returns a struct{} map containing all values read from ch as keys. -// It is a shorthand for ToKeyMap(ch, func(k K) struct{} { return struct{}{} }) +// It is a shorthand for ToMap(ch, func(value T) (T, struct{}) { return value, struct{}{} }) func ToStructMap[T comparable](ch <-chan T) map[T]struct{} { - return ToKeyMap(ch, func(key T) struct{} { return struct{}{} }) + return ToMap(ch, func(value T) (T, struct{}) { return value, struct{}{} }) }