github.com/kubeshop/testkube@v1.17.23/internal/common/common.go (about)

     1  package common
     2  
     3  import "reflect"
     4  
     5  // MergeMaps merges multiple maps into one, the later ones takes precedence over the first ones
     6  func MergeMaps(ms ...map[string]string) map[string]string {
     7  	res := map[string]string{}
     8  	for _, m := range ms {
     9  		for k, v := range m {
    10  			res[k] = v
    11  		}
    12  	}
    13  	return res
    14  }
    15  
    16  func Ptr[T any](v T) *T {
    17  	return &v
    18  }
    19  
    20  func MapPtr[T any, U any](v *T, fn func(T) U) *U {
    21  	if v == nil {
    22  		return nil
    23  	}
    24  	return Ptr(fn(*v))
    25  }
    26  
    27  func PtrOrNil[T any](v T) *T {
    28  	if reflect.ValueOf(v).IsZero() {
    29  		return nil
    30  	}
    31  	return &v
    32  }
    33  
    34  func ResolvePtr[T any](v *T, def T) T {
    35  	if v == nil {
    36  		return def
    37  	}
    38  	return *v
    39  }
    40  
    41  func MapSlice[T any, U any](s []T, fn func(T) U) []U {
    42  	if len(s) == 0 {
    43  		return nil
    44  	}
    45  	result := make([]U, len(s))
    46  	for i := range s {
    47  		result[i] = fn(s[i])
    48  	}
    49  	return result
    50  }
    51  
    52  func FilterSlice[T any](s []T, fn func(T) bool) []T {
    53  	if len(s) == 0 {
    54  		return nil
    55  	}
    56  	result := make([]T, 0)
    57  	for i := range s {
    58  		if fn(s[i]) {
    59  			result = append(result, s[i])
    60  		}
    61  	}
    62  	return result
    63  }
    64  
    65  func UniqueSlice[T comparable](s []T) []T {
    66  	if len(s) == 0 {
    67  		return nil
    68  	}
    69  	result := make([]T, 0)
    70  	seen := map[T]struct{}{}
    71  	for i := range s {
    72  		_, ok := seen[s[i]]
    73  		if !ok {
    74  			seen[s[i]] = struct{}{}
    75  			result = append(result, s[i])
    76  		}
    77  	}
    78  	return result
    79  }
    80  
    81  func MapMap[T any, U any](m map[string]T, fn func(T) U) map[string]U {
    82  	if len(m) == 0 {
    83  		return nil
    84  	}
    85  	res := make(map[string]U, len(m))
    86  	for k, v := range m {
    87  		res[k] = fn(v)
    88  	}
    89  	return res
    90  }
    91  
    92  func GetMapValue[T any, K comparable](m map[K]T, k K, def T) T {
    93  	v, ok := m[k]
    94  	if ok {
    95  		return v
    96  	}
    97  	return def
    98  }
    99  
   100  func GetOr(v ...string) string {
   101  	for i := range v {
   102  		if v[i] != "" {
   103  			return v[i]
   104  		}
   105  	}
   106  	return ""
   107  }