mirror of
https://github.com/kovidgoyal/kitty
synced 2026-06-08 22:28:24 +02:00
Utility function to sort with key
This commit is contained in:
@@ -5,6 +5,8 @@ package utils
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
"golang.org/x/exp/constraints"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
@@ -33,3 +35,21 @@ func StableSort[T any](s []T, less func(a, b T) bool) []T {
|
||||
sort.SliceStable(s, func(i, j int) bool { return less(s[i], s[j]) })
|
||||
return s
|
||||
}
|
||||
|
||||
func SortWithKey[T any, C constraints.Ordered](s []T, key func(a T) C) []T {
|
||||
mem := make([]C, len(s))
|
||||
for i, x := range s {
|
||||
mem[i] = key(x)
|
||||
}
|
||||
sort.Slice(s, func(i, j int) bool { return mem[i] < mem[j] })
|
||||
return s
|
||||
}
|
||||
|
||||
func StableSortWithKey[T any, C constraints.Ordered](s []T, key func(a T) C) []T {
|
||||
mem := make([]C, len(s))
|
||||
for i, x := range s {
|
||||
mem[i] = key(x)
|
||||
}
|
||||
sort.SliceStable(s, func(i, j int) bool { return mem[i] < mem[j] })
|
||||
return s
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user