mirror of
https://github.com/SagerNet/sing.git
synced 2025-04-05 04:47:40 +03:00
Add sortBy/minBy/maxBy
This commit is contained in:
parent
bc109486f1
commit
b85bdb9af7
2 changed files with 95 additions and 0 deletions
|
@ -4,7 +4,10 @@ import (
|
|||
"context"
|
||||
"io"
|
||||
"runtime"
|
||||
"sort"
|
||||
"unsafe"
|
||||
|
||||
"github.com/sagernet/sing/common/x/constraints"
|
||||
)
|
||||
|
||||
func Any[T any](array []T, block func(it T) bool) bool {
|
||||
|
@ -161,6 +164,48 @@ func UniqBy[T any, C comparable](arr []T, block func(it T) C) []T {
|
|||
return result
|
||||
}
|
||||
|
||||
func SortBy[T any, C constraints.Ordered](arr []T, block func(it T) C) {
|
||||
sort.Slice(arr, func(i, j int) bool {
|
||||
return block(arr[i]) < block(arr[j])
|
||||
})
|
||||
}
|
||||
|
||||
func MinBy[T any, C constraints.Ordered](arr []T, block func(it T) C) T {
|
||||
var min T
|
||||
var minValue C
|
||||
if len(arr) == 0 {
|
||||
return min
|
||||
}
|
||||
min = arr[0]
|
||||
for i := 1; i < len(arr); i++ {
|
||||
item := arr[i]
|
||||
value := block(item)
|
||||
if value < minValue {
|
||||
min = item
|
||||
minValue = value
|
||||
}
|
||||
}
|
||||
return min
|
||||
}
|
||||
|
||||
func MaxBy[T any, C constraints.Ordered](arr []T, block func(it T) C) T {
|
||||
var max T
|
||||
var maxValue C
|
||||
if len(arr) == 0 {
|
||||
return max
|
||||
}
|
||||
max = arr[0]
|
||||
for i := 1; i < len(arr); i++ {
|
||||
item := arr[i]
|
||||
value := block(item)
|
||||
if value > maxValue {
|
||||
max = item
|
||||
maxValue = value
|
||||
}
|
||||
}
|
||||
return max
|
||||
}
|
||||
|
||||
func FilterIsInstance[T any, N any](arr []T, block func(it T) (N, bool)) []N {
|
||||
var retArr []N
|
||||
for _, it := range arr {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue