fix(groupbymap): remove second iteratee and add test+example+doc

This commit is contained in:
Samuel Berthe
2025-01-28 20:25:04 +01:00
parent 19cb99199d
commit ce12685a40
4 changed files with 50 additions and 7 deletions

View File

@@ -92,6 +92,7 @@ Supported helpers for slices:
- [Uniq](#uniq)
- [UniqBy](#uniqby)
- [GroupBy](#groupby)
- [GroupByMap](#groupbymap)
- [Chunk](#chunk)
- [PartitionBy](#partitionby)
- [Flatten](#flatten)
@@ -566,6 +567,19 @@ lop.GroupBy([]int{0, 1, 2, 3, 4, 5}, func(i int) int {
// map[int][]int{0: []int{0, 3}, 1: []int{1, 4}, 2: []int{2, 5}}
```
### GroupByMap
Returns an object composed of keys generated from the results of running each element of collection through iteratee.
```go
import lo "github.com/samber/lo"
groups := lo.GroupByMap([]int{0, 1, 2, 3, 4, 5}, func(i int) (int, int) {
return i%3, i*2
})
// map[int][]int{0: []int{0, 6}, 1: []int{2, 8}, 2: []int{4, 10}}
```
### Chunk
Returns an array of elements split into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements.

View File

@@ -188,18 +188,15 @@ func GroupBy[T any, U comparable, Slice ~[]T](collection Slice, iteratee func(it
return result
}
// GroupByMapValues returns an object composed of keys generated from the results of running each element of collection through iterateeKey and values running each element through iterateeValue.
func GroupByMapValues[K comparable, T any, V any](arr []T, iterateeKey func(T) K, iterateeValue func(T) V) map[K][]V {
// GroupByMap returns an object composed of keys generated from the results of running each element of collection through iteratee.
func GroupByMap[T any, K comparable, V any](arr []T, iteratee func(item T) (K, V)) map[K][]V {
result := map[K][]V{}
for _, item := range arr {
k := iterateeKey(item)
v := iterateeValue(item)
k, v := iteratee(item)
result[k] = append(result[k], v)
}
return result
}

View File

@@ -165,6 +165,22 @@ func ExampleGroupBy() {
// [2 5]
}
func ExampleGroupByMap() {
list := []int{0, 1, 2, 3, 4, 5}
result := GroupByMap(list, func(i int) (int, int) {
return i % 3, i * 2
})
fmt.Printf("%v\n", result[0])
fmt.Printf("%v\n", result[1])
fmt.Printf("%v\n", result[2])
// Output:
// [0 6]
// [2 8]
// [4 10]
}
func ExampleChunk() {
list := []int{0, 1, 2, 3, 4}

View File

@@ -254,6 +254,22 @@ func TestGroupBy(t *testing.T) {
is.IsType(nonempty[42], allStrings, "type preserved")
}
func TestGroupByMap(t *testing.T) {
t.Parallel()
is := assert.New(t)
result1 := GroupByMap([]int{0, 1, 2, 3, 4, 5}, func(i int) (int, string) {
return i % 3, strconv.Itoa(i)
})
is.Equal(len(result1), 3)
is.Equal(result1, map[int][]string{
0: {"0", "3"},
1: {"1", "4"},
2: {"2", "5"},
})
}
func TestChunk(t *testing.T) {
t.Parallel()
is := assert.New(t)