mirror of
https://github.com/kovidgoyal/kitty.git
synced 2026-08-03 22:25:57 +00:00
Some more useful generic slice utilities
This commit is contained in:
parent
601a333b0e
commit
32e0a56a94
1 changed files with 31 additions and 0 deletions
|
|
@ -7,6 +7,7 @@ import (
|
|||
"sort"
|
||||
|
||||
"golang.org/x/exp/constraints"
|
||||
"golang.org/x/exp/slices"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
|
@ -26,6 +27,36 @@ func Reversed[T any](s []T) []T {
|
|||
return ans
|
||||
}
|
||||
|
||||
func Remove[T comparable](s []T, q T) []T {
|
||||
idx := slices.Index(s, q)
|
||||
if idx > -1 {
|
||||
return slices.Delete(s, idx, idx+1)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func RemoveAll[T comparable](s []T, q T) []T {
|
||||
ans := s
|
||||
for {
|
||||
idx := slices.Index(ans, q)
|
||||
if idx < 0 {
|
||||
break
|
||||
}
|
||||
ans = slices.Delete(ans, idx, idx+1)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func Filter[T any](s []T, f func(x T) bool) []T {
|
||||
ans := make([]T, 0, len(s))
|
||||
for _, x := range s {
|
||||
if f(x) {
|
||||
ans = append(ans, x)
|
||||
}
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func Sort[T any](s []T, less func(a, b T) bool) []T {
|
||||
sort.Slice(s, func(i, j int) bool { return less(s[i], s[j]) })
|
||||
return s
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue