aboutsummaryrefslogtreecommitdiffstats
path: root/library/go/slices/filter.go
blob: 8b383bfcb2680749df4e55484fac7201c0f328cc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package slices

import (
	"golang.org/x/exp/slices"
)

// Filter reduces slice values using given function.
// It operates with a copy of given slice
func Filter[S ~[]T, T any](s S, fn func(T) bool) S {
	if len(s) == 0 {
		return s
	}
	return Reduce(slices.Clone(s), fn)
}

// Reduce is like Filter, but modifies original slice.
func Reduce[S ~[]T, T any](s S, fn func(T) bool) S {
	if len(s) == 0 {
		return s
	}
	var p int
	for _, v := range s {
		if fn(v) {
			s[p] = v
			p++
		}
	}
	return s[:p]
}