feat: adding WithoutNth (#575)

This commit is contained in:
Samuel Berthe
2025-01-25 18:18:48 +01:00
committed by GitHub
parent 0362663557
commit 8e64522eb6
3 changed files with 59 additions and 1 deletions

View File

@@ -210,6 +210,7 @@ Supported intersection helpers:
- [Union](#union)
- [Without](#without)
- [WithoutEmpty](#withoutempty)
- [WithoutNth](#withoutnth)
Supported search helpers:
@@ -2164,6 +2165,15 @@ subset := lo.WithoutEmpty([]int{0, 2, 10})
// []int{2, 10}
```
### WithoutNth
Returns slice excluding nth value.
```go
subset := lo.WithoutNth([]int{-2, -1, 0, 1, 2}, 3, -42, 1)
// []int{-2, 0, 2}
```
### 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.

View File

@@ -167,9 +167,14 @@ func Union[T comparable, Slice ~[]T](lists ...Slice) Slice {
// Without returns slice excluding all given values.
func Without[T comparable, Slice ~[]T](collection Slice, exclude ...T) Slice {
excludeMap := make(map[T]struct{}, len(exclude))
for i := range exclude {
excludeMap[exclude[i]] = struct{}{}
}
result := make(Slice, 0, len(collection))
for i := range collection {
if !Contains(exclude, collection[i]) {
if _, ok := excludeMap[collection[i]]; !ok {
result = append(result, collection[i])
}
}
@@ -182,3 +187,24 @@ func Without[T comparable, Slice ~[]T](collection Slice, exclude ...T) Slice {
func WithoutEmpty[T comparable, Slice ~[]T](collection Slice) Slice {
return Compact(collection)
}
// WithoutNth returns slice excluding nth value.
func WithoutNth[T comparable, Slice ~[]T](collection Slice, nths ...int) Slice {
length := len(collection)
toRemove := make(map[int]struct{}, len(nths))
for i := range nths {
if nths[i] >= 0 && nths[i] <= length-1 {
toRemove[nths[i]] = struct{}{}
}
}
result := make(Slice, 0, len(collection))
for i := range collection {
if _, ok := toRemove[i]; !ok {
result = append(result, collection[i])
}
}
return result
}

View File

@@ -286,3 +286,25 @@ func TestWithoutEmpty(t *testing.T) {
nonempty := WithoutEmpty(allStrings)
is.IsType(nonempty, allStrings, "type preserved")
}
func TestWithoutNth(t *testing.T) {
t.Parallel()
is := assert.New(t)
result1 := WithoutNth([]int{5, 6, 7}, 1, 0)
is.Equal([]int{7}, result1)
result2 := WithoutNth([]int{1, 2})
is.Equal([]int{1, 2}, result2)
result3 := WithoutNth([]int{})
is.Equal([]int{}, result3)
result4 := WithoutNth([]int{0, 1, 2, 3}, -1, 4)
is.Equal([]int{0, 1, 2, 3}, result4)
type myStrings []string
allStrings := myStrings{"", "foo", "bar"}
nonempty := WithoutNth(allStrings)
is.IsType(nonempty, allStrings, "type preserved")
}