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

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