gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/stream/filter/filter.go (about)

     1  package filter
     2  
     3  import (
     4  	"gitee.com/sy_183/go-common/generic"
     5  	"gitee.com/sy_183/go-common/stream"
     6  	unsafeUtil "gitee.com/sy_183/go-common/unsafe"
     7  )
     8  
     9  func Unique[V comparable]() stream.Filter[V] {
    10  	set := make(map[V]struct{})
    11  	return func(v V) bool {
    12  		if _, has := set[v]; !has {
    13  			set[v] = struct{}{}
    14  			return true
    15  		}
    16  		return false
    17  	}
    18  }
    19  
    20  func UniqueBy[V any, K comparable](kf func(v V) K) stream.Filter[V] {
    21  	set := make(map[K]struct{})
    22  	return func(v V) bool {
    23  		k := kf(v)
    24  		if _, has := set[k]; !has {
    25  			set[k] = struct{}{}
    26  			return true
    27  		}
    28  		return false
    29  	}
    30  }
    31  
    32  func UniqueOffset[V any, K comparable](offset uintptr) stream.Filter[V] {
    33  	set := make(map[K]struct{})
    34  	return func(v V) bool {
    35  		k := unsafeUtil.Offset[V, K](&v, offset)
    36  		if _, has := set[k]; !has {
    37  			set[k] = struct{}{}
    38  			return true
    39  		}
    40  		return false
    41  	}
    42  }
    43  
    44  func Equal[V comparable](v V) stream.Filter[V] {
    45  	return func(value V) bool { return value == v }
    46  }
    47  
    48  func NotEqual[V comparable](v V) stream.Filter[V] {
    49  	return func(value V) bool { return value != v }
    50  }
    51  
    52  func Greater[V generic.Ordered](v V) stream.Filter[V] {
    53  	return func(value V) bool { return value > v }
    54  }
    55  
    56  func Less[V generic.Ordered](v V) stream.Filter[V] {
    57  	return func(value V) bool { return value < v }
    58  }
    59  
    60  func GreaterOrEqual[V generic.Ordered](v V) stream.Filter[V] {
    61  	return func(value V) bool { return value >= v }
    62  }
    63  
    64  func LessOrEqual[V generic.Ordered](v V) stream.Filter[V] {
    65  	return func(value V) bool { return value <= v }
    66  }