Add function Without which return slice with slice all elements not i… (#142)

* Add function Without which return slice with slice all elements not in another

* feat(Without): inverse args and use variadic argment for excluding items

Co-authored-by: Samuel Berthe <dev@samuel-berthe.fr>
This commit is contained in:
chensy
2022-07-04 16:17:03 +08:00
committed by GitHub
parent 5bdd1c13c9
commit 07fddc1640
3 changed files with 38 additions and 0 deletions

View File

@@ -138,6 +138,7 @@ Supported intersection helpers:
- Intersect - Intersect
- Difference - Difference
- Union - Union
- Without
Supported search helpers: Supported search helpers:
@@ -1088,6 +1089,18 @@ union := lo.Union[int]([]int{0, 1, 2, 3, 4, 5}, []int{0, 2, 10})
// []int{0, 1, 2, 3, 4, 5, 10} // []int{0, 1, 2, 3, 4, 5, 10}
``` ```
### Without
Returns slice excluding all given values.
```go
subset := lo.Without[int]([]int{0, 2, 10}, 2)
// []int{0, 10}
subset := lo.Without[int]([]int{0, 2, 10}, 0, 1, 2, 3, 4, 5)
// []int{10}
```
### IndexOf ### IndexOf
Returns the index at which the first occurrence of a value is found in an array or return -1 if the value cannot be found. Returns the index at which the first occurrence of a value is found in an array or return -1 if the value cannot be found.

View File

@@ -175,3 +175,14 @@ func Union[T comparable](list1 []T, list2 []T) []T {
return result return result
} }
// Without returns slice excluding all given values.
func Without[T comparable](collection []T, exclude ...T) []T {
result := make([]T, 0, len(collection))
for _, e := range collection {
if !Contains(exclude, e) {
result = append(result, e)
}
}
return result
}

View File

@@ -209,3 +209,17 @@ func TestUnion(t *testing.T) {
is.Equal(result4, []int{0, 1, 2}) is.Equal(result4, []int{0, 1, 2})
is.Equal(result5, []int{}) is.Equal(result5, []int{})
} }
func TestWithout(t *testing.T) {
is := assert.New(t)
result1 := Without([]int{0, 2, 10}, 0, 1, 2, 3, 4, 5)
result2 := Without([]int{0, 7}, 0, 1, 2, 3, 4, 5)
result3 := Without([]int{}, 0, 1, 2, 3, 4, 5)
result4 := Without([]int{0, 1, 2}, 0, 1, 2)
result5 := Without([]int{})
is.Equal(result1, []int{10})
is.Equal(result2, []int{7})
is.Equal(result3, []int{})
is.Equal(result4, []int{})
is.Equal(result5, []int{})
}