2023-10-20 13:41:06 +02:00
|
|
|
package lib
|
|
|
|
|
|
|
|
// MapToSlice converts a map to a slice in go
|
|
|
|
func MapValues[K comparable, V any](m map[K]V) []V {
|
|
|
|
return MapValuesWithExclude(m, map[K]struct{}{})
|
|
|
|
}
|
|
|
|
|
|
|
|
func MapValuesWithExclude[K comparable, V any](m map[K]V, exclude map[K]struct{}) []V {
|
|
|
|
values := make([]V, len(m)-len(exclude))
|
|
|
|
|
|
|
|
i := 0
|
2023-10-21 19:08:45 +02:00
|
|
|
|
|
|
|
if len(m)-len(exclude) <= 0 {
|
|
|
|
return values
|
|
|
|
}
|
|
|
|
|
2023-10-20 13:41:06 +02:00
|
|
|
for k, v := range m {
|
|
|
|
if _, excluded := exclude[k]; excluded {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
values[i] = v
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
|
|
|
|
return values
|
|
|
|
}
|
2023-10-25 19:34:38 +02:00
|
|
|
|
|
|
|
func MapKeys[K comparable, V any](m map[K]V) []K {
|
|
|
|
values := make([]K, len(m))
|
|
|
|
|
|
|
|
i := 0
|
2023-11-05 13:08:20 +01:00
|
|
|
for k := range m {
|
2023-10-25 19:34:38 +02:00
|
|
|
values[i] = k
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
|
|
|
|
return values
|
|
|
|
}
|
2023-10-31 11:34:09 +01:00
|
|
|
|
|
|
|
type convert[V1 any, V2 any] func(V1) V2
|
|
|
|
|
2023-11-03 16:24:18 +01:00
|
|
|
// Map turns a list of type V1 into type V2
|
2023-10-31 11:34:09 +01:00
|
|
|
func Map[V1 any, V2 any](list []V1, f convert[V1, V2]) []V2 {
|
|
|
|
newList := make([]V2, len(list))
|
|
|
|
|
|
|
|
for i, elem := range list {
|
|
|
|
newList[i] = f(elem)
|
|
|
|
}
|
|
|
|
|
|
|
|
return newList
|
|
|
|
}
|
2023-11-03 16:24:18 +01:00
|
|
|
|
|
|
|
type filterFunc[V any] func(V) bool
|
|
|
|
|
|
|
|
// Filter filters out elements given a filter function.
|
|
|
|
// If filter function is true keep it in otherwise leave it out
|
|
|
|
func Filter[V any](list []V, f filterFunc[V]) []V {
|
|
|
|
newList := make([]V, 0)
|
|
|
|
|
2023-11-05 13:08:20 +01:00
|
|
|
for _, elem := range list {
|
2023-11-03 16:24:18 +01:00
|
|
|
if f(elem) {
|
|
|
|
newList = append(newList, elem)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return newList
|
|
|
|
}
|