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

feat: add SortbyKeys for map

This commit is contained in:
dudaodong
2024-08-23 11:21:29 +08:00
parent 30971c1aab
commit 3e8c3bd396
5 changed files with 151 additions and 0 deletions

View File

@@ -56,6 +56,7 @@ import (
- [ConcurrentMap_Has](#ConcurrentMap_Has)
- [ConcurrentMap_Range](#ConcurrentMap_Range)
- [GetOrSet](#GetOrSet)
- [SortByKeys](#SortByKeys)
<div STYLE="page-break-after: always;"></div>
@@ -1522,4 +1523,41 @@ func main() {
// a
// b
}
```
### <span id="SortByKeys">SortByKeys</span>
<p>对传入的map根据key进行排序返回排序后的map。</p>
<b>函数签名:</b>
```go
func SortByKeys[K constraints.Ordered, V any](m map[K]V) (sortedKeysMap map[K]V)
```
<b>示例:<span style="float:right;display:inline-block;">[运行]()</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/maputil"
)
func main() {
m := map[int]string{
3: "c",
1: "a",
4: "d",
2: "b",
}
result := maputil.SortByKeys(m)
fmt.Println(result)
// Output:
// map[1:a 2:b 3:c 4:d]
}
```

View File

@@ -1538,4 +1538,41 @@ func main() {
// a
// b
}
```
### <span id="SortByKeys">SortByKeys</span>
<p>Sorts the map by its keys and returns a new map with sorted keys.</p>
<b>Signature:</b>
```go
func SortByKeys[K constraints.Ordered, V any](m map[K]V) (sortedKeysMap map[K]V)
```
<b>Example:<span style="float:right;display:inline-block;">[运行]()</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/maputil"
)
func main() {
m := map[int]string{
3: "c",
1: "a",
4: "d",
2: "b",
}
result := maputil.SortByKeys(m)
fmt.Println(result)
// Output:
// map[1:a 2:b 3:c 4:d]
}
```

View File

@@ -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
}

View File

@@ -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]
}

View File

@@ -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)
}