Rename MapMap and new map func
Renamed MapMap to MapSameKeys to increase clarity for usage Added func MapNewKeys to allow making a map with new keys too
This commit is contained in:
parent
66a118e6ef
commit
b3db20785b
1 changed files with 19 additions and 3 deletions
|
@ -2,9 +2,10 @@ package maputils
|
|||
|
||||
import "gitlab.com/mstarongitlab/goutils/sliceutils"
|
||||
|
||||
// MapMap applies a given function to every key-value pair of a map.
|
||||
// The returned map's value type may be different from the type of the inital map's value.
|
||||
func MapMap[K comparable, V any, R any](dic map[K]V, apply func(K, V) R) map[K]R {
|
||||
// MapSameKeys applies a given function to every key-value pair of a map.
|
||||
// The returned map's value type may be different from the type of the inital map's value
|
||||
// But it will keep the same keys as the input map
|
||||
func MapSameKeys[K comparable, V any, R any](dic map[K]V, apply func(K, V) R) map[K]R {
|
||||
n := make(map[K]R, len(dic))
|
||||
for key, val := range dic {
|
||||
n[key] = apply(key, val)
|
||||
|
@ -12,6 +13,21 @@ func MapMap[K comparable, V any, R any](dic map[K]V, apply func(K, V) R) map[K]R
|
|||
return n
|
||||
}
|
||||
|
||||
// MapNewKeys applies a given function to every key-value pair of a map.
|
||||
// The returned map's keys and values may be of different types as the input map
|
||||
// The first return value of the apply func will be used as new key, the second as the value
|
||||
func MapNewKeys[Kin comparable, Vin any, Kout comparable, Vout any](
|
||||
in map[Kin]Vin,
|
||||
apply func(Kin, Vin) (Kout, Vout),
|
||||
) map[Kout]Vout {
|
||||
n := make(map[Kout]Vout, len(in))
|
||||
for ki, vi := range in {
|
||||
ko, vo := apply(ki, vi)
|
||||
n[ko] = vo
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// FilterMap filters a map using a given function.
|
||||
// If the filter function returns true, the key-value pair stays, otherwise it gets removed.
|
||||
func FilterMap[K comparable, V any](dic map[K]V, filter func(K, V) bool) map[K]V {
|
||||
|
|
Loading…
Reference in a new issue