ToMap refactored
This commit is contained in:
parent
dbfd7d6cd3
commit
15e4d83ab9
21
to.go
21
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{}{} })
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user