more filter functions

This commit is contained in:
milarin 2024-05-14 20:26:58 +02:00
parent 78436e629c
commit 87bc148570

View File

@ -1,6 +1,6 @@
package channel package channel
func Filter[T any](source <-chan T, filter func(T) bool) <-chan T { func FilterSuccessive[T any](source <-chan T, filter func(T) bool) <-chan T {
out := make(chan T, cap(source)) out := make(chan T, cap(source))
go func() { go func() {
@ -14,3 +14,26 @@ func Filter[T any](source <-chan T, filter func(T) bool) <-chan T {
return out return out
} }
func Filter[T any](source <-chan T, filter func(T) bool) <-chan T {
return FilterPreserveOrderWithRunner(source, getDefaultRunner(), filter)
}
func FilterPreserveOrderWithRunner[T any](source <-chan T, runner Runner, filter func(T) bool) <-chan T {
type FilteredValue[T any] struct {
Value T
Filter bool
}
mappedValues := MapPreserveOrderWithRunner(source, runner, func(value T) FilteredValue[T] {
return FilteredValue[T]{Value: value, Filter: filter(value)}
})
filteredValues := FilterSuccessive(mappedValues, func(filteredValue FilteredValue[T]) bool {
return filteredValue.Filter
})
return MapSuccessive(filteredValues, func(filteredValue FilteredValue[T]) T {
return filteredValue.Value
})
}