blob: b7ee5da546cc13bf4cda44d67db2e61e579e577f [file] [log] [blame]
// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package functools
import (
"cmp"
"slices"
)
// Filter returns a new slice containing all the elements of `original` for
// which `f` returns true.
func Filter[T any](original []T, f func(T) bool) []T {
var filtered []T
for _, element := range original {
if f(element) {
filtered = append(filtered, element)
}
}
return filtered
}
// SortBy sorts the given slice in-place, using the return value of `getter`
// as the key by which elements are sorted.
func SortBy[T any, C cmp.Ordered](slice []T, getter func(T) C) {
slices.SortFunc(slice, func(a, b T) int {
return cmp.Compare(getter(a), getter(b))
})
}