code.gitea.io/gitea@v1.22.3/modules/container/filter.go (about)

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