mirror of
https://github.com/rjNemo/underscore
synced 2026-06-06 02:26:42 +00:00
feat: partition
This commit is contained in:
parent
b26a360495
commit
e626c0c47e
3 changed files with 40 additions and 0 deletions
|
|
@ -21,3 +21,4 @@ It is mostly a port from the `underscore.js` library based on generics brought b
|
|||
- `contains` (only numerics values at the moment)
|
||||
- `max`
|
||||
- `min`
|
||||
- `partition`
|
||||
|
|
|
|||
17
partition.go
Normal file
17
partition.go
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
package underscore
|
||||
|
||||
// Partition splits the slice into two slices: one whose elements all satisfy predicate
|
||||
// and one whose elements all do not satisfy predicate.
|
||||
func Partition[T any](values []T, predicate func(T) bool) ([]T, []T) {
|
||||
keep := make([]T, 0)
|
||||
reject := make([]T, 0)
|
||||
|
||||
for _, v := range values {
|
||||
if predicate(v) {
|
||||
keep = append(keep, v)
|
||||
} else {
|
||||
reject = append(reject, v)
|
||||
}
|
||||
}
|
||||
return keep, reject
|
||||
}
|
||||
22
partition_test.go
Normal file
22
partition_test.go
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
package underscore_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
u "github.com/rjNemo/underscore"
|
||||
)
|
||||
|
||||
func TestPartition(t *testing.T) {
|
||||
nums := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
|
||||
isEven := func(n int) bool { return n%2 == 0 }
|
||||
|
||||
wantEvens := []int{0, 2, 4, 6, 8}
|
||||
wantOdds := []int{1, 3, 5, 7, 9}
|
||||
|
||||
evens, odds := u.Partition(nums, isEven)
|
||||
|
||||
assert.Equal(t, wantEvens, evens)
|
||||
assert.Equal(t, wantOdds, odds)
|
||||
}
|
||||
Loading…
Reference in a new issue