collectors added
This commit is contained in:
parent
a89b395510
commit
962249789b
52
to.go
Normal file
52
to.go
Normal file
@ -0,0 +1,52 @@
|
||||
package channel
|
||||
|
||||
import "container/list"
|
||||
|
||||
// ToSlice returns a slice containing all values read from ch
|
||||
func ToSlice[T any](ch <-chan T) []T {
|
||||
s := make([]T, 0, cap(ch))
|
||||
Each(ch, func(value T) { s = append(s, value) })
|
||||
return s
|
||||
}
|
||||
|
||||
// ToSliceDeref returns a slice containing all values read from ch.
|
||||
// The returned slice will be a dereferenced and continuous block of memory.
|
||||
// Nil pointers are ignored.
|
||||
func ToSliceDeref[T any](ch <-chan *T) []T {
|
||||
s := make([]T, 0, cap(ch))
|
||||
Each(ch, func(value *T) {
|
||||
if value != nil {
|
||||
s = append(s, *value)
|
||||
}
|
||||
})
|
||||
return s
|
||||
}
|
||||
|
||||
// ToList returns a list.List containing all values read from ch
|
||||
func ToList[T any](ch <-chan T) *list.List {
|
||||
l := list.New()
|
||||
Each(ch, func(value T) { l.PushBack(value) })
|
||||
return l
|
||||
}
|
||||
|
||||
// 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 {
|
||||
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) })
|
||||
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{}{} })
|
||||
func ToStructMap[T comparable](ch <-chan T) map[T]struct{} {
|
||||
return ToKeyMap(ch, func(key T) struct{} { return struct{}{} })
|
||||
}
|
Loading…
Reference in New Issue
Block a user