diff --git a/tools/utils/misc.go b/tools/utils/misc.go index 5a107cb57..ca5b8702b 100644 --- a/tools/utils/misc.go +++ b/tools/utils/misc.go @@ -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