generics/maps.go

51 lines
910 B
Go
Raw Normal View History

2023-11-03 21:18:22 +01:00
package generics
2024-05-28 00:20:32 +02:00
// MapPairs returns list of map's key-value pairs.
2024-05-21 22:39:52 +02:00
func MapPairs[K comparable, V any](src map[K]V) Pairs[K, V] {
2023-11-03 21:18:22 +01:00
dst := make([]Pair[K, V], len(src))
idx := 0
for k, v := range src {
dst[idx] = Pair[K, V]{
Key: k,
Value: v,
}
idx++
}
return dst
}
2024-05-28 00:20:32 +02:00
// MapKeys returns list of map's keys.
2023-11-03 21:18:22 +01:00
func MapKeys[K comparable, V any](src map[K]V) []K {
dst := make([]K, len(src))
idx := 0
for k := range src {
dst[idx] = k
idx++
}
return dst
}
2024-05-28 00:20:32 +02:00
// MapValues returns list of map's values.
2023-11-03 21:18:22 +01:00
func MapValues[K comparable, V any](src map[K]V) []V {
dst := make([]V, len(src))
idx := 0
for _, v := range src {
dst[idx] = v
idx++
}
return dst
}
2024-05-28 00:20:32 +02:00
// InvertMap returns map with keys and values swapped.
2023-11-03 21:18:22 +01:00
func InvertMap[K, V comparable](src map[K]V) map[V]K {
if src == nil {
return nil
}
dst := make(map[V]K, len(src))
for k, v := range src {
dst[v] = k
}
return dst
}