gitee.com/quant1x/gox@v1.21.2/api/slices_sort.go (about)

     1  package api
     2  
     3  import (
     4  	"reflect"
     5  	"slices"
     6  	"sort"
     7  )
     8  
     9  // SliceSort slice排序
    10  func SliceSort[S ~[]E, E any](slice S, less func(a, b E) bool) {
    11  	sort.Slice(slice, func(i, j int) bool {
    12  		a := slice[i]
    13  		b := slice[j]
    14  		return less(a, b)
    15  	})
    16  }
    17  
    18  // SliceUnique sorts the slice pointed by the provided pointer given the provided
    19  // less function and removes repeated elements.
    20  // The function panics if the provided interface is not a pointer to a slice.
    21  func v1SliceUnique[S ~[]E, E any](slicePtr *S, less func(i, j int) bool) {
    22  	v := reflect.ValueOf(slicePtr).Elem()
    23  	if v.Len() <= 1 {
    24  		return
    25  	}
    26  	sort.Slice(v.Interface(), less)
    27  
    28  	i := 0
    29  	for j := 1; j < v.Len(); j++ {
    30  		if !less(i, j) {
    31  			continue
    32  		}
    33  		i++
    34  		v.Index(i).Set(v.Index(j))
    35  	}
    36  	i++
    37  	v.SetLen(i)
    38  }
    39  
    40  func SliceUnique[S ~[]E, E any](slice S, compare func(a E, b E) int) S {
    41  	//v := reflect.ValueOf(&slice).Elem()
    42  	//slices.SortFunc()
    43  	slices.SortFunc(slice, compare)
    44  	s := slices.CompactFunc(slice, func(a E, b E) bool {
    45  		return compare(a, b) == 0
    46  	})
    47  	return s
    48  }