add groupBy function (#28)

This commit is contained in:
Ruidy 2022-04-20 16:23:59 -04:00 committed by GitHub
parent 7fef1562f2
commit e5b3ad8ef1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 0 deletions

15
groupby.go Normal file
View file

@ -0,0 +1,15 @@
package underscore
// GroupBy splits a slice into a map[K][]V grouped by the result of the iterator function.
func GroupBy[K comparable, V any](values []V, f func(V) K) map[K][]V {
res := make(map[K][]V, 0)
for _, v := range values {
k := f(v)
if r, ok := res[k]; ok {
res[k] = append(r, v)
} else {
res[k] = []V{v}
}
}
return res
}

22
groupby_test.go Normal file
View file

@ -0,0 +1,22 @@
package underscore_test
import (
"math"
"testing"
"github.com/stretchr/testify/assert"
u "github.com/rjNemo/underscore"
)
func TestGroupBy(t *testing.T) {
nums := []float64{1.3, 2.1, 2.4}
want := map[int][]float64{
1: {1.3},
2: {2.1, 2.4},
}
f := func(n float64) int {
return int(math.Floor(n))
}
assert.Equal(t, want, u.GroupBy(nums, f))
}