mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-15 02:02:27 +08:00
feat: add KeysBy function
This commit is contained in:
@@ -34,6 +34,18 @@ func Values[K comparable, V any](m map[K]V) []V {
|
|||||||
return values
|
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.
|
// 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 {
|
||||||
|
|||||||
@@ -41,6 +41,24 @@ func TestValues(t *testing.T) {
|
|||||||
assert.Equal([]string{"a", "a", "b", "c", "d"}, values)
|
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) {
|
func TestMerge(t *testing.T) {
|
||||||
assert := internal.NewAssert(t, "TestMerge")
|
assert := internal.NewAssert(t, "TestMerge")
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user