mirror of
https://github.com/samber/lo.git
synced 2025-09-27 04:15:58 +08:00
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:
13
README.md
13
README.md
@@ -138,6 +138,7 @@ Supported intersection helpers:
|
||||
- Intersect
|
||||
- Difference
|
||||
- Union
|
||||
- Without
|
||||
|
||||
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}
|
||||
```
|
||||
|
||||
### 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
|
||||
|
||||
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.
|
||||
|
11
intersect.go
11
intersect.go
@@ -175,3 +175,14 @@ func Union[T comparable](list1 []T, list2 []T) []T {
|
||||
|
||||
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
|
||||
}
|
||||
|
@@ -209,3 +209,17 @@ func TestUnion(t *testing.T) {
|
||||
is.Equal(result4, []int{0, 1, 2})
|
||||
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{})
|
||||
}
|
||||
|
Reference in New Issue
Block a user