github.com/richardwilkes/toolbox@v1.121.0/collection/dict/more.go (about)

     1  // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the Mozilla Public
     4  // License, version 2.0. If a copy of the MPL was not distributed with
     5  // this file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  //
     7  // This Source Code Form is "Incompatible With Secondary Licenses", as
     8  // defined by the Mozilla Public License, version 2.0.
     9  
    10  package dict
    11  
    12  // MapByKey returns a map of the values in 'data' keyed by the result of keyFunc. If there are duplicate keys, the last
    13  // value in data with that key will be the one in the map.
    14  func MapByKey[T any, K comparable](data []T, keyFunc func(T) K) map[K]T {
    15  	m := make(map[K]T)
    16  	for _, v := range data {
    17  		m[keyFunc(v)] = v
    18  	}
    19  	return m
    20  }
    21  
    22  // MapOfSlicesByKey returns a map of the values in 'data' keyed by the result of keyFunc. Duplicate keys will have their
    23  // values appended to a slice in the map.
    24  func MapOfSlicesByKey[T any, K comparable](data []T, keyFunc func(T) K) map[K][]T {
    25  	m := make(map[K][]T)
    26  	for _, v := range data {
    27  		k := keyFunc(v)
    28  		m[k] = append(m[k], v)
    29  	}
    30  	return m
    31  }