mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-08 22:52:29 +08:00
feat: add SortbyKeys for map
This commit is contained in:
@@ -453,3 +453,23 @@ func GetOrSet[K comparable, V any](m map[K]V, key K, value V) V {
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
// SortByKeys sorts the map by its keys and returns a new map with sorted keys.
|
||||
// Play: todo
|
||||
func SortByKeys[K constraints.Ordered, V any](m map[K]V) (sortedKeysMap map[K]V) {
|
||||
keys := make([]K, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
|
||||
sort.Slice(keys, func(i, j int) bool {
|
||||
return keys[i] < keys[j]
|
||||
})
|
||||
|
||||
sortedKeysMap = make(map[K]V, len(m))
|
||||
for _, k := range keys {
|
||||
sortedKeysMap[k] = m[k]
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -540,3 +540,19 @@ func ExampleGetOrSet() {
|
||||
// a
|
||||
// b
|
||||
}
|
||||
|
||||
func ExampleSortByKeys() {
|
||||
m := map[int]string{
|
||||
3: "c",
|
||||
1: "a",
|
||||
4: "d",
|
||||
2: "b",
|
||||
}
|
||||
|
||||
result := SortByKeys(m)
|
||||
|
||||
fmt.Println(result)
|
||||
|
||||
// Output:
|
||||
// map[1:a 2:b 3:c 4:d]
|
||||
}
|
||||
|
||||
@@ -707,3 +707,43 @@ func TestGetOrSet(t *testing.T) {
|
||||
assert.Equal("a", result1)
|
||||
assert.Equal("b", result2)
|
||||
}
|
||||
|
||||
func TestSortByKeys(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
assert := internal.NewAssert(t, "TestSortByKeys")
|
||||
|
||||
m1 := map[int]string{
|
||||
3: "c",
|
||||
1: "a",
|
||||
4: "d",
|
||||
2: "b",
|
||||
}
|
||||
expected1 := map[int]string{
|
||||
1: "a",
|
||||
2: "b",
|
||||
3: "c",
|
||||
4: "d",
|
||||
}
|
||||
|
||||
result1 := SortByKeys(m1)
|
||||
|
||||
assert.Equal(expected1, result1)
|
||||
|
||||
m2 := map[string]int{
|
||||
"c": 3,
|
||||
"a": 1,
|
||||
"d": 4,
|
||||
"b": 2,
|
||||
}
|
||||
expected2 := map[string]int{
|
||||
"a": 1,
|
||||
"b": 2,
|
||||
"c": 3,
|
||||
"d": 4,
|
||||
}
|
||||
|
||||
result2 := SortByKeys(m2)
|
||||
|
||||
assert.Equal(expected2, result2)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user