goutils/pkg/maputils/mapUtils.go

58 lines
1.4 KiB
Go
Raw Normal View History

package maps
2022-08-07 19:59:43 +00:00
import "gitlab.com/beckersam/goutils/pkg/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 {
n := make(map[K]R, len(dic))
for key, val := range dic {
n[key] = apply(key, val)
}
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 {
n := make(map[K]V, 0)
for key, val := range dic {
if filter(key, val) {
n[key] = val
}
}
return n
}
// KeysFromMap creates a slice of keys that match the keys in a given map.
func KeysFromMap[K comparable, V any](m map[K]V) []K {
keys := make([]K, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
return keys
}
// CompareMap compares two maps for key-val equality (If both maps have the same key-value pairs).
func CompareMap[K, V comparable](a, b map[K]V) bool {
if len(a) != len(b) {
return false
}
// Check if both maps have the same keys
if !sliceutils.CompareUnorderedSlice(KeysFromMap(a), KeysFromMap(b)) {
return false
}
// Then compare key-value pairs
for k, v := range a {
val, ok := b[k]
if !(ok && val == v) {
return false
}
}
return true
}