diff --git a/maputil/map.go b/maputil/map.go index 1d595ce..1dbc211 100644 --- a/maputil/map.go +++ b/maputil/map.go @@ -226,3 +226,27 @@ func Transform[K1 comparable, V1 any, K2 comparable, V2 any](m map[K1]V1, iterat return result } + +// MapKeys transforms a map to other type map by manipulating it's keys. +// Play: todo +func MapKeys[K comparable, V any, T comparable](m map[K]V, iteratee func(key K, value V) T) map[T]V { + result := make(map[T]V, len(m)) + + for k, v := range m { + result[iteratee(k, v)] = v + } + + return result +} + +// MapValues transforms a map to other type map by manipulating it's values. +// Play: todo +func MapValues[K comparable, V any, T any](m map[K]V, iteratee func(key K, value V) T) map[K]T { + result := make(map[K]T, len(m)) + + for k, v := range m { + result[k] = iteratee(k, v) + } + + return result +} diff --git a/maputil/map_test.go b/maputil/map_test.go index cdcd9be..e27f1c4 100644 --- a/maputil/map_test.go +++ b/maputil/map_test.go @@ -311,3 +311,47 @@ func TestTransform(t *testing.T) { assert.Equal(expected, result) } + +func TestMapKeys(t *testing.T) { + assert := internal.NewAssert(t, "TestMapKeys") + + m := map[int]string{ + 1: "a", + 2: "b", + 3: "c", + } + + result := MapKeys(m, func(k int, _ string) string { + return strconv.Itoa(k) + }) + + expected := map[string]string{ + "1": "a", + "2": "b", + "3": "c", + } + + assert.Equal(expected, result) +} + +func TestMapValues(t *testing.T) { + assert := internal.NewAssert(t, "TestMapKeys") + + m := map[int]string{ + 1: "a", + 2: "b", + 3: "c", + } + + result := MapValues(m, func(k int, v string) string { + return v + strconv.Itoa(k) + }) + + expected := map[int]string{ + 1: "a1", + 2: "b2", + 3: "c3", + } + + assert.Equal(expected, result) +}