Skip to content

Commit

Permalink
Merge pull request #13 from carlossantin/slice-to-map-grouped-by
Browse files Browse the repository at this point in the history
Add conversion of slices to map grouping by field
  • Loading branch information
orsinium committed May 11, 2023
2 parents aa90d61 + 944a4d0 commit d104098
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
11 changes: 11 additions & 0 deletions slices/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,17 @@ func ToMap[S ~[]V, V any](items S) map[int]V {
return result
}

// ToMapGroupedBy converts the given slice into a map where keys are values returned
// from keyExtractor function and values are items from the given slice
func ToMapGroupedBy[V any, T comparable](items []V, keyExtractor func(V) T) map[T][]V {
result := make(map[T][]V)
for _, item := range items {
key := keyExtractor(item)
result[key] = append(result[key], item)
}
return result
}

// ToKeys converts the given slice into a map where items from the slice are the keys
// of the resulting map and all values are equal to the given `val` value.
func ToKeys[S ~[]K, K comparable, V any](items S, val V) map[K]V {
Expand Down
29 changes: 29 additions & 0 deletions slices/slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -532,3 +532,32 @@ func TestWithout(t *testing.T) {

f([]int{1, 1, 2, 3, 1, 4, 1}, []int{1}, []int{2, 3, 4})
}

func TestToMapGroupedBy(t *testing.T) {
is := is.New(t)

type employee struct {
Name string
Department string
}

f := func(given []employee, expected map[string][]employee) {
actual := slices.ToMapGroupedBy(given, func(emp employee) string {
return emp.Department
})
is.Equal(expected, actual)
}

employeeJohn := employee{Name: "John", Department: "Engineering"}
employeeEva := employee{Name: "Eva", Department: "HR"}
employeeCarlos := employee{Name: "Carlos", Department: "Engineering"}

f([]employee{employeeJohn, employeeEva, employeeCarlos}, map[string][]employee{
"Engineering": {employeeJohn, employeeCarlos},
"HR": {employeeEva},
})

f([]employee{}, map[string][]employee{})

f(nil, map[string][]employee{})
}

0 comments on commit d104098

Please sign in to comment.