| // 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 ( |
| "golang.org/x/exp/constraints" |
| "golang.org/x/exp/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 constraints.Ordered](slice []T, getter func(T) C) { |
| slices.SortFunc(slice, func(a, b T) bool { |
| return getter(a) < getter(b) |
| }) |
| } |