-
Notifications
You must be signed in to change notification settings - Fork 2
/
filter.go
58 lines (45 loc) · 1.63 KB
/
filter.go
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package simpleflow
// FilterSliceInplace filters the input slice with the function `fn` in-place
// The function `fn` accepts a value and should return true to keep the value in the slice
func FilterSliceInplace[V any](in []V, fn func(v V) bool) []V {
return FilterSliceInto(in, in[:0], fn)
}
// FilterSlice filters the input slice with the function `fn` and return a new slice
// The function `fn` accepts a value and should return true to copy the value into the new slice
func FilterSlice[V any](in []V, fn func(v V) bool) []V {
var out []V
return FilterSliceInto(in, out, fn)
}
// FilterSliceInto filters the input slice `in` with the function `fn` into `out`
// The function `fn` accepts a value and should return true to copy the value into the `out` slice
func FilterSliceInto[V any](in, out []V, fn func(v V) bool) []V {
var count int
for ii := 0; ii < len(in); ii++ {
if !fn(in[ii]) {
continue
}
out = append(out, in[ii])
count++
}
return out[:count]
}
// FilterMapInplace filters the input map with the function `fn` in-place
// The function `fn` accepts a key, value pair and should return true to keep the pair in the map
func FilterMapInplace[K comparable, V any](in map[K]V, fn func(k K, v V) bool) {
for k, v := range in {
if !fn(k, v) {
delete(in, k)
}
}
}
// FilterMap filters the input map with the function `fn` and return a new map
// The function `fn` accepts a key, value pair and should return true to keep the pair in the map
func FilterMap[K comparable, V any](in map[K]V, fn func(k K, v V) bool) map[K]V {
var out = map[K]V{}
for k, v := range in {
if fn(k, v) {
out[k] = v
}
}
return out
}