mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
feat: add MapKeys and MapValues
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user