1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-09 07:02:29 +08:00

feat: add Sort function for slice

This commit is contained in:
dudaodong
2022-12-01 22:46:56 +08:00
parent d66f92cd68
commit ec27ad4c40
4 changed files with 77 additions and 1 deletions

View File

@@ -10,6 +10,8 @@ import (
"math/rand"
"reflect"
"sort"
"github.com/duke-git/lancet/v2/lancetconstraints"
)
// Contain check if the target value is in the slice or not
@@ -713,8 +715,18 @@ func Shuffle[T any](slice []T) []T {
return result
}
// Sort sorts a slice of any ordered type(number or string), use quick sort algrithm.
// default sort order is ascending (asc), if want descending order, set param `sortOrder` to `desc`
func Sort[T lancetconstraints.Ordered](slice []T, sortOrder ...string) {
if len(sortOrder) > 0 && sortOrder[0] == "desc" {
quickSort(slice, 0, len(slice)-1, "desc")
} else {
quickSort(slice, 0, len(slice)-1, "asc")
}
}
// SortByField return sorted slice by field
// Slice element should be struct, field type should be int, uint, string, or bool
// slice element should be struct, field type should be int, uint, string, or bool
// default sortType is ascending (asc), if descending order, set sortType to desc
func SortByField(slice any, field string, sortType ...string) error {
sv := sliceValue(slice)