mirror of
https://github.com/kovidgoyal/kitty.git
synced 2026-08-04 14:46:03 +00:00
Utility function to sort with key
This commit is contained in:
parent
e7f38929d9
commit
b1e08adbce
3 changed files with 29 additions and 6 deletions
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue