wp-go/helper/slice/sort.go

87 lines
1.4 KiB
Go
Raw Permalink Normal View History

2023-01-21 11:31:23 +00:00
package slice
2023-02-28 11:19:24 +00:00
import (
"golang.org/x/exp/constraints"
"sort"
)
const (
ASC = "asc"
DESC = "desc"
2023-02-28 11:19:24 +00:00
)
2023-01-21 11:31:23 +00:00
type anyArr[T any] struct {
data []T
fn func(i, j T) bool
}
func (r anyArr[T]) Len() int {
return len(r.data)
}
func (r anyArr[T]) Swap(i, j int) {
r.data[i], r.data[j] = r.data[j], r.data[i]
}
func (r anyArr[T]) Less(i, j int) bool {
return r.fn(r.data[i], r.data[j])
}
2023-10-14 06:57:57 +00:00
// Sort fn i>j 为降序 desc反之为升序 asc
2023-03-02 12:36:58 +00:00
func Sort[T any](arr []T, fn func(i, j T) bool) {
2023-01-21 11:31:23 +00:00
slice := anyArr[T]{
2023-03-02 12:36:58 +00:00
data: arr,
2023-01-21 11:31:23 +00:00
fn: fn,
}
sort.Sort(slice)
2023-05-10 09:02:58 +00:00
}
func StableSort[T any](arr []T, fn func(i, j T) bool) {
slice := anyArr[T]{
data: arr,
fn: fn,
}
sort.Stable(slice)
2023-01-21 11:31:23 +00:00
}
2023-02-28 11:19:24 +00:00
func Sorts[T constraints.Ordered](a []T, order string) {
2023-02-28 11:19:24 +00:00
slice := anyArr[T]{
data: a,
fn: func(i, j T) bool {
if order == DESC {
return i > j
}
return i < j
},
}
sort.Sort(slice)
}
func SortsNew[T constraints.Ordered](a []T, order string) []T {
r := make([]T, len(a))
copy(r, a)
slice := anyArr[T]{
data: r,
fn: func(i, j T) bool {
if order == DESC {
return i > j
}
return i < j
},
}
sort.Sort(slice)
return r
}
func SimpleSort[T any, O constraints.Ordered](a []T, order string, fn func(t T) O) {
slice := anyArr[T]{
data: a,
fn: func(i, j T) bool {
if order == DESC {
return fn(i) > fn(j)
}
return fn(i) < fn(j)
},
}
sort.Sort(slice)
}