Request: Remove in place
The idea is to remove elements from a slice without making a new slice.
func RemoveInPlace[T any](collection []T, predicate func(T) bool) []T {
i := 0
for _, x := range collection {
if !predicate(x) {
collection[i] = x
i++
}
}
return collection[:i]
}
I'd be happy to send a PR I wasn't sure about what good name would work. May be Delete or Remove ?
I'm not a big fan of mutable helpers for such a library.
Can you create a sub-package please? Also, I think we must rename this function into Filter instead of Remove.
import (
"github.com/samber/lo"
lop "github.com/samber/lo/parallel"
lom "github.com/samber/lo/mutable"
)
lom.Filter(collection, func (item, index) bool {
return false
})
It could be useful to return the length of the slice.
Let's see if we get more traction, I like the mutable idea 👍 .
I expect more people to want this at high scale to avoid allocations but if this is niche I'll be happy to avoid the complexity.
@samber @cyriltovena That's a good proposal, I think. How about implementing it this way? If it is not a problem, I will try to PR it.
package mutable
func Filter[V any](collection []V, predicate func(item V, index int) bool) ([]V, int) {
size := 0
for i, item := range collection {
if predicate(item, i) {
collection[size] = item
size++
}
}
return collection[:size], size
}