gitea源码

filter.go 679B

12345678910111213141516171819202122
  1. // Copyright 2024 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package container
  4. import "slices"
  5. // FilterSlice ranges over the slice and calls include() for each element.
  6. // If the second returned value is true, the first returned value will be included in the resulting
  7. // slice (after deduplication).
  8. func FilterSlice[E any, T comparable](s []E, include func(E) (T, bool)) []T {
  9. filtered := make([]T, 0, len(s)) // slice will be clipped before returning
  10. seen := make(map[T]bool, len(s))
  11. for i := range s {
  12. if v, ok := include(s[i]); ok && !seen[v] {
  13. filtered = append(filtered, v)
  14. seen[v] = true
  15. }
  16. }
  17. return slices.Clip(filtered)
  18. }