slices/to.go

43 lines
1.1 KiB
Go
Raw Normal View History

2022-09-06 01:58:19 +02:00
package slices
import (
"container/list"
)
// Deref returns a slice containing all dereferenced values of s.
// The returned slice will be a dereferenced and continuous block of memory.
// Nil pointers are ignored.
func Deref[T any](s []*T) []T {
out := make([]T, 0, len(s))
Each(s, func(v *T) {
if v != nil {
out = append(out, *v)
}
})
return out
}
// ToList returns a list.List containing all values of s
func ToList[T any](s []T) *list.List {
l := list.New()
Each(s, func(value T) { l.PushBack(value) })
return l
}
// ToMap returns a map containing all values of s.
// The map key-value pairs are determined by mapper
func ToMap[T any, K comparable, V any](s []T, mapper func(T) (K, V)) map[K]V {
m := map[K]V{}
Each(s, func(value T) {
k, v := mapper(value)
m[k] = v
})
return m
}
// ToStructMap returns a struct{} map containing all values of s as keys.
// It is a shorthand for ToMap(s, func(value T) (T, struct{}) { return value, struct{}{} })
func ToStructMap[T comparable](s []T) map[T]struct{} {
return ToMap(s, func(value T) (T, struct{}) { return value, struct{}{} })
}