diff --git a/README.md b/README.md index 24e4ce3..afcbdb5 100644 --- a/README.md +++ b/README.md @@ -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` diff --git a/partition.go b/partition.go new file mode 100644 index 0000000..ebc038e --- /dev/null +++ b/partition.go @@ -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 +} diff --git a/partition_test.go b/partition_test.go new file mode 100644 index 0000000..136e2c5 --- /dev/null +++ b/partition_test.go @@ -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) +}