mirror of
https://github.com/Monibuca/engine.git
synced 2025-12-24 13:18:07 +08:00
加入排序Range函数 RangeSorted
This commit is contained in:
30
util/map.go
30
util/map.go
@@ -1,6 +1,9 @@
|
|||||||
package util
|
package util
|
||||||
|
|
||||||
import "sync"
|
import (
|
||||||
|
"sort"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
type Map[K comparable, V any] struct {
|
type Map[K comparable, V any] struct {
|
||||||
sync.Map
|
sync.Map
|
||||||
@@ -66,3 +69,28 @@ func (m *Map[K, V]) Range(f func(K, V)) {
|
|||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *Map[K, V]) RangeSorted(f func(K, V), compare func(K, K) bool) {
|
||||||
|
// Collect keys and values
|
||||||
|
var pairs []struct {
|
||||||
|
key K
|
||||||
|
val V
|
||||||
|
}
|
||||||
|
m.Map.Range(func(k, v interface{}) bool {
|
||||||
|
pairs = append(pairs, struct {
|
||||||
|
key K
|
||||||
|
val V
|
||||||
|
}{k.(K), v.(V)})
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
|
||||||
|
// Sort by keys using the compare function
|
||||||
|
sort.Slice(pairs, func(i, j int) bool {
|
||||||
|
return compare(pairs[i].key, pairs[j].key)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Apply function in sorted order
|
||||||
|
for _, pair := range pairs {
|
||||||
|
f(pair.key, pair.val)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user