github.com/searKing/golang/go@v1.2.74/container/slice/filter.go (about)

     1  // Copyright 2020 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package slice
     6  
     7  import (
     8  	"github.com/searKing/golang/go/util/object"
     9  )
    10  
    11  // FilterFunc returns a slice consisting of the elements of this slice that match
    12  // the given predicate.
    13  func FilterFunc(s interface{}, f func(interface{}) bool) interface{} {
    14  	return normalizeSlice(filterFunc(Of(s), f, true), s)
    15  }
    16  
    17  // filterFunc is the same as FilterFunc except that if
    18  // truth==false, the sense of the predicate function is
    19  // inverted.
    20  func filterFunc(s []interface{}, f func(interface{}) bool, truth bool) []interface{} {
    21  	object.RequireNonNil(s, "filterFunc called on nil slice")
    22  	object.RequireNonNil(f, "filterFunc called on nil callfn")
    23  
    24  	var sFiltered = []interface{}{}
    25  	for _, r := range s {
    26  		if f(r) == truth {
    27  			sFiltered = append(sFiltered, r)
    28  		}
    29  	}
    30  	return sFiltered
    31  }