Passed
Pull Request — master (#93)
by Hayrullah
02:09
created

group_by.go   A

Size/Duplication

Total Lines 16
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
dl 0
loc 16
rs 10
c 0
b 0
f 0
1
package gotil
2
3
// GroupBy iterates over elements of collection, returns an map object.
4
// key is result of iterator method
5
// value is list
6
// 	result := gotil.GroupBy([]int{10, 20, 30}, func(v int, i int) int {
7
// 	return v / 10
8
// 	})
9
// 	fmt.Println(result)
10
// 	// Output: map[1:[10] 2:[20] 3:[30]]
11
func GroupBy[T, K comparable](s []T, f func(v T, i int) K) map[K][]T {
12
	result := map[K][]T{}
13
	for i, v := range s {
14
		key := f(v, i)
15
		result[key] = append(result[key], v)
16
	}
17
	return result
18
}
19