Some more useful generic slice utilities

This commit is contained in:
Kovid Goyal 2023-02-10 21:46:35 +05:30
parent 601a333b0e
commit 32e0a56a94
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C

View File

@ -7,6 +7,7 @@ import (
"sort" "sort"
"golang.org/x/exp/constraints" "golang.org/x/exp/constraints"
"golang.org/x/exp/slices"
) )
var _ = fmt.Print var _ = fmt.Print
@ -26,6 +27,36 @@ func Reversed[T any](s []T) []T {
return ans 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 { 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]) }) sort.Slice(s, func(i, j int) bool { return less(s[i], s[j]) })
return s return s