mirror of
https://github.com/samber/lo.git
synced 2025-09-27 04:15:58 +08:00
feat: adding WithoutNth (#575)
This commit is contained in:
28
intersect.go
28
intersect.go
@@ -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
|
||||
}
|
||||
|
Reference in New Issue
Block a user