lo icon indicating copy to clipboard operation
lo copied to clipboard

Request: Remove in place

Open cyriltovena opened this issue 3 years ago • 2 comments

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 ?

cyriltovena avatar Jul 18 '22 07:07 cyriltovena

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.

samber avatar Jul 24 '22 19:07 samber

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.

cyriltovena avatar Jul 25 '22 07:07 cyriltovena

@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
}

ss49919201 avatar Mar 02 '23 13:03 ss49919201