github.com/TBD54566975/ftl@v0.219.0/internal/slices/slices.go (about)

     1  package slices
     2  
     3  func Map[T, U any](slice []T, fn func(T) U) []U {
     4  	result := make([]U, len(slice))
     5  	for i, v := range slice {
     6  		result[i] = fn(v)
     7  	}
     8  	return result
     9  }
    10  
    11  func MapErr[T, U any](slice []T, fn func(T) (U, error)) ([]U, error) {
    12  	result := make([]U, len(slice))
    13  	for i, v := range slice {
    14  		var err error
    15  		result[i], err = fn(v)
    16  		if err != nil {
    17  			return nil, err
    18  		}
    19  	}
    20  	return result, nil
    21  }
    22  
    23  func Filter[T any](slice []T, fn func(T) bool) []T {
    24  	result := make([]T, 0, len(slice))
    25  	for _, v := range slice {
    26  		if fn(v) {
    27  			result = append(result, v)
    28  		}
    29  	}
    30  	return result
    31  }
    32  
    33  // GroupBy groups the elements of a slice by the result of a function.
    34  func GroupBy[T any, K comparable](slice []T, fn func(T) K) map[K][]T {
    35  	result := make(map[K][]T)
    36  	for _, v := range slice {
    37  		key := fn(v)
    38  		result[key] = append(result[key], v)
    39  	}
    40  	return result
    41  }
    42  
    43  func Reduce[T, U any](slice []T, initial U, fn func(U, T) U) U {
    44  	result := initial
    45  	for _, v := range slice {
    46  		result = fn(result, v)
    47  	}
    48  	return result
    49  }
    50  
    51  // AppendOrReplace appends a value to a slice if the slice does not contain a
    52  // value for which the given function returns true. If the slice does contain
    53  // such a value, it is replaced.
    54  func AppendOrReplace[T any](slice []T, value T, fn func(T) bool) []T {
    55  	for i, v := range slice {
    56  		if fn(v) {
    57  			slice[i] = value
    58  			return slice
    59  		}
    60  	}
    61  	return append(slice, value)
    62  }
    63  
    64  func FlatMap[T, U any](slice []T, fn func(T) []U) []U {
    65  	result := make([]U, 0, len(slice))
    66  	for _, v := range slice {
    67  		result = append(result, fn(v)...)
    68  	}
    69  	return result
    70  }
    71  
    72  func Find[T any](slice []T, fn func(T) bool) (T, bool) {
    73  	for _, v := range slice {
    74  		if fn(v) {
    75  			return v, true
    76  		}
    77  	}
    78  	var zero T
    79  	return zero, false
    80  }