Skip to content

Commit

Permalink
slices: + ToMultimapWithKeys
Browse files Browse the repository at this point in the history
  • Loading branch information
mikhalytch committed Jul 8, 2024
1 parent 6255fab commit bd134ad
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
16 changes: 16 additions & 0 deletions slices/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,19 @@ func ToMapWithKeys[K comparable, V any](keyProducer func(V) K) funcs.Applier[[]V
return res
}
}

func ToMultimapWithKeys[K comparable, V any](keyProducer func(V) K) funcs.Applier[[]V, map[K][]V] {
return func(vs []V) map[K][]V {
res := make(map[K][]V, 0)

for _, v := range vs {
key := keyProducer(v)

ex := res[key]
ex = append(ex, v)
res[key] = ex
}

return res
}
}
12 changes: 12 additions & 0 deletions slices/map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,15 @@ func TestToMapWithKeys(t *testing.T) {
require.Equal(t, map[string]int{"a": 0, "b": 1},
slices.ToMapWithKeys(func(v int) string { return string([]byte{byte(v + 'a')}) })([]int{0, 1}))
}

func TestToMultimapWithKeys(t *testing.T) {
require.Empty(t, slices.ToMultimapWithKeys(func(_ int) string { return "" })([]int{}))
require.Empty(t, slices.ToMultimapWithKeys(func(_ int) string { return "" })(nil))

require.Equal(t,
map[string][]int{"1": {1}},
slices.ToMultimapWithKeys(strconv.StoA[int])([]int{1}))
require.Equal(t,
map[string][]int{"1": {1, 1}, "2": {2, 2, 2}},
slices.ToMultimapWithKeys(strconv.StoA[int])([]int{1, 2, 2, 2, 1}))
}

0 comments on commit bd134ad

Please sign in to comment.