Skip to content

Commit

Permalink
feat: add slice.Remove
Browse files Browse the repository at this point in the history
  • Loading branch information
Primetalk committed Feb 7, 2023
1 parent 3ff90fd commit 5f4c9bf
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,7 @@ Some utilities that are convenient when working with slices.
- `slice.Reduce[A any](as []A, f func(A, A) A) A` - Reduce aggregates all elements pairwise. Only works for non empty slices.
- `slice.Filter[A any](as []A, p func(a A) bool) (res []A)`
- `slice.FilterNot[A any](as []A, p func(a A) bool) (res []A)` - same as `Filter`, but inverses the predicate `p`.
- `slice.Remove[A comparable](as []A, r []A) (res []A)` - Remove removes any elements in r from as.
- `slice.Partition[A any](as []A, p fun.Predicate[A]) (resT []A, resF []A)` - Partition separates elements in as according to the predicate.
- `slice.Exists[A any](p fun.Predicate[A]) fun.Predicate[[]A]` - Exists returns a predicate on slices. The predicate is true if there is an element that satisfy the given element-wise predicate. It's false for an empty slice.
- `slice.Forall[A any](p fun.Predicate[A]) fun.Predicate[[]A]` - Forall returns a predicate on slices. The predicate is true if all elements satisfy the given element-wise predicate. It's true for an empty slice.
Expand Down
6 changes: 6 additions & 0 deletions slice/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -280,3 +280,9 @@ func Reverse[A any](as []A) (res []A) {
}
return
}

// Remove removes any elements in r from as.
func Remove[A comparable](as []A, r []A) (res []A) {
sr := ToSet(r)
return FilterNot(as, set.Contains(sr))
}
7 changes: 7 additions & 0 deletions slice/slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,10 @@ func TestReverse(t *testing.T) {
znats2 := slice.Range(0, 2)
assert.ElementsMatch(t, []int{1, 0}, slice.Reverse(znats2))
}

func TestRemove(t *testing.T) {
znats10 := slice.Range(0, 10)
znats5 := slice.Range(0, 5)
znats510 := slice.Range(5, 10)
assert.ElementsMatch(t, znats510, slice.Remove(znats10, znats5))
}

0 comments on commit 5f4c9bf

Please sign in to comment.