mirror of
https://github.com/openimsdk/open-im-server.git
synced 2025-05-19 02:39:27 +08:00
1
This commit is contained in:
parent
c3f6a0fa15
commit
0eb77e9b35
@ -1,5 +1,9 @@
|
||||
package utilsv2
|
||||
|
||||
import (
|
||||
"sort"
|
||||
)
|
||||
|
||||
// DistinctAny 切片去重
|
||||
func DistinctAny[T any, V comparable](ts []T, fn func(t T) V) []T {
|
||||
v := make([]T, 0, len(ts))
|
||||
@ -105,3 +109,44 @@ func MapValue[K comparable, V any](kv map[K]V) []V {
|
||||
}
|
||||
return vs
|
||||
}
|
||||
|
||||
// Sort 排序
|
||||
func Sort[T Ordered](ts []T, asc bool) []T {
|
||||
SortAny(ts, func(a, b T) bool {
|
||||
if asc {
|
||||
return a < b
|
||||
} else {
|
||||
return a > b
|
||||
}
|
||||
})
|
||||
return ts
|
||||
}
|
||||
|
||||
// SortAny 排序
|
||||
func SortAny[T any](ts []T, fn func(a, b T) bool) {
|
||||
sort.Sort(&sortSlice[T]{
|
||||
ts: ts,
|
||||
fn: fn,
|
||||
})
|
||||
}
|
||||
|
||||
type sortSlice[T any] struct {
|
||||
ts []T
|
||||
fn func(a, b T) bool
|
||||
}
|
||||
|
||||
func (o *sortSlice[T]) Len() int {
|
||||
return len(o.ts)
|
||||
}
|
||||
|
||||
func (o *sortSlice[T]) Less(i, j int) bool {
|
||||
return o.fn(o.ts[i], o.ts[j])
|
||||
}
|
||||
|
||||
func (o *sortSlice[T]) Swap(i, j int) {
|
||||
o.ts[i], o.ts[j] = o.ts[j], o.ts[i]
|
||||
}
|
||||
|
||||
type Ordered interface {
|
||||
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~float32 | ~float64 | ~string
|
||||
}
|
||||
|
@ -42,3 +42,9 @@ func TestIndexOf(t *testing.T) {
|
||||
fmt.Println(IndexOf(arr, 3))
|
||||
|
||||
}
|
||||
|
||||
func TestSort(t *testing.T) {
|
||||
arr := []int{1, 1, 1, 4, 4, 5, 2, 3, 3, 3, 6}
|
||||
fmt.Println(Sort(arr, false))
|
||||
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user