1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-09 15:12:26 +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

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