1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 21:02:27 +08:00

feat: add KeysBy function

This commit is contained in:
dudaodong
2023-02-17 11:40:20 +08:00
parent 572e53aa14
commit e71cecefea
2 changed files with 30 additions and 0 deletions

View File

@@ -34,6 +34,18 @@ func Values[K comparable, V any](m map[K]V) []V {
return values
}
// KeysBy creates a slice whose element is the result of function mapper invoked by every map's key.
// todo:
func KeysBy[K comparable, V any, T any](m map[K]V, mapper func(item K) T) []T {
keys := make([]T, 0, len(m))
for k := range m {
keys = append(keys, mapper(k))
}
return keys
}
// Merge maps, next key will overwrite previous key.
// Play: https://go.dev/play/p/H95LENF1uB-
func Merge[K comparable, V any](maps ...map[K]V) map[K]V {

View File

@@ -41,6 +41,24 @@ func TestValues(t *testing.T) {
assert.Equal([]string{"a", "a", "b", "c", "d"}, values)
}
func TestKeysBy(t *testing.T) {
assert := internal.NewAssert(t, "TestKeysBy")
m := map[int]string{
1: "a",
2: "a",
3: "b",
}
keys := KeysBy(m, func(n int) int {
return n + 1
})
sort.Ints(keys)
assert.Equal([]int{2, 3, 4}, keys)
}
func TestMerge(t *testing.T) {
assert := internal.NewAssert(t, "TestMerge")