github.com/searKing/golang/go@v1.2.74/container/slice/sorted.go (about) 1 // Copyright 2020 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package slice 6 7 import ( 8 "sort" 9 10 "github.com/searKing/golang/go/util/object" 11 ) 12 13 // SortedFunc returns a slice consisting of the distinct elements (according to 14 // {@link Object#equals(Object)}) of this slice. 15 // s: Accept Array、Slice、String(as []byte if ifStringAsRune else []rune) 16 func SortedFunc(s interface{}, f func(interface{}, interface{}) int) interface{} { 17 return normalizeSlice(sortedFunc(Of(s), f), s) 18 } 19 20 // sortedFunc is the same as SortedFunc except that if 21 // truth==false, the sense of the predicate function is 22 // inverted. 23 func sortedFunc(s []interface{}, f func(interface{}, interface{}) int) []interface{} { 24 object.RequireNonNil(s, "distinctFunc called on nil slice") 25 object.RequireNonNil(f, "distinctFunc called on nil callfn") 26 27 less := func(i, j int) bool { 28 if f(s[i], s[j]) < 0 { 29 return true 30 } 31 return false 32 } 33 sort.Slice(s, less) 34 return s 35 }