mirror of
https://github.com/duke-git/lancet.git
synced 2026-03-01 00:35:28 +08:00
feat: add ValuesBy function
This commit is contained in:
@@ -46,6 +46,18 @@ func KeysBy[K comparable, V any, T any](m map[K]V, mapper func(item K) T) []T {
|
|||||||
return keys
|
return keys
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ValuesBy creates a slice whose element is the result of function mapper invoked by every map's value.
|
||||||
|
// todo:
|
||||||
|
func ValuesBy[K comparable, V any, T any](m map[K]V, mapper func(item V) T) []T {
|
||||||
|
keys := make([]T, 0, len(m))
|
||||||
|
|
||||||
|
for _, v := range m {
|
||||||
|
keys = append(keys, mapper(v))
|
||||||
|
}
|
||||||
|
|
||||||
|
return keys
|
||||||
|
}
|
||||||
|
|
||||||
// Merge maps, next key will overwrite previous key.
|
// Merge maps, next key will overwrite previous key.
|
||||||
// Play: https://go.dev/play/p/H95LENF1uB-
|
// Play: https://go.dev/play/p/H95LENF1uB-
|
||||||
func Merge[K comparable, V any](maps ...map[K]V) map[K]V {
|
func Merge[K comparable, V any](maps ...map[K]V) map[K]V {
|
||||||
|
|||||||
@@ -59,6 +59,33 @@ func TestKeysBy(t *testing.T) {
|
|||||||
assert.Equal([]int{2, 3, 4}, keys)
|
assert.Equal([]int{2, 3, 4}, keys)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestValuesBy(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestValuesBy")
|
||||||
|
|
||||||
|
m := map[int]string{
|
||||||
|
1: "a",
|
||||||
|
2: "b",
|
||||||
|
3: "c",
|
||||||
|
}
|
||||||
|
|
||||||
|
values := ValuesBy(m, func(v string) string {
|
||||||
|
switch v {
|
||||||
|
case "a":
|
||||||
|
return "a-1"
|
||||||
|
case "b":
|
||||||
|
return "b-2"
|
||||||
|
case "c":
|
||||||
|
return "c-3"
|
||||||
|
default:
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
sort.Strings(values)
|
||||||
|
|
||||||
|
assert.Equal([]string{"a-1", "b-2", "c-3"}, values)
|
||||||
|
}
|
||||||
|
|
||||||
func TestMerge(t *testing.T) {
|
func TestMerge(t *testing.T) {
|
||||||
assert := internal.NewAssert(t, "TestMerge")
|
assert := internal.NewAssert(t, "TestMerge")
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user