github.com/wfusion/gofusion@v1.1.14/common/utils/map.go (about)

     1  package utils
     2  
     3  func MapKeys[T comparable, K any](m map[T]K) (keys []T) {
     4  	if m == nil {
     5  		return
     6  	}
     7  	keys = make([]T, 0, len(m))
     8  	for key := range m {
     9  		keys = append(keys, key)
    10  	}
    11  	return
    12  }
    13  
    14  func MapValues[T comparable, K any](m map[T]K) (vals []K) {
    15  	if m == nil {
    16  		return
    17  	}
    18  	vals = make([]K, 0, len(m))
    19  	for _, val := range m {
    20  		vals = append(vals, val)
    21  	}
    22  	return
    23  }
    24  
    25  func MapValuesByKeys[T comparable, K any, TS ~[]T](m map[T]K, keys TS) (vals []K) {
    26  	if m == nil {
    27  		return
    28  	}
    29  	vals = make([]K, 0, len(keys))
    30  	for _, key := range keys {
    31  		val, ok := m[key]
    32  		if !ok {
    33  			continue
    34  		}
    35  		vals = append(vals, val)
    36  	}
    37  	return
    38  }
    39  
    40  func MapMerge[T comparable, K any](a, b map[T]K) (r map[T]K) {
    41  	r = make(map[T]K, len(a)+len(b))
    42  	for k, v := range a {
    43  		r[k] = v
    44  	}
    45  	for k, v := range b {
    46  		r[k] = v
    47  	}
    48  	return
    49  }
    50  
    51  func MapSliceToMap[T comparable, K any](s []map[T]K) (d map[T]K) {
    52  	d = make(map[T]K, len(s))
    53  	for _, kv := range s {
    54  		for k, v := range kv {
    55  			d[k] = v
    56  		}
    57  	}
    58  	return
    59  }
    60  
    61  func SliceToMap[K comparable, V any](s []V, groupFn func(v V) K) (d map[K]V) {
    62  	d = make(map[K]V)
    63  	for _, i := range s {
    64  		d[groupFn(i)] = i
    65  	}
    66  	return
    67  }