diff --git a/README.md b/README.md index e81041d..487aae5 100644 --- a/README.md +++ b/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. diff --git a/intersect.go b/intersect.go index eac1639..68e0f32 100644 --- a/intersect.go +++ b/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 +} diff --git a/intersect_test.go b/intersect_test.go index 80f12ee..9904d90 100644 --- a/intersect_test.go +++ b/intersect_test.go @@ -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{}) +}