...

Source file src/github.com/thoas/go-funk/predicate.go

Documentation: github.com/thoas/go-funk

     1  package funk
     2  
     3  import (
     4  	"reflect"
     5  )
     6  
     7  // predicatesImpl contains the common implementation of AnyPredicates and AllPredicates.
     8  func predicatesImpl(value interface{}, wantedAnswer bool, predicates interface{}) bool {
     9  	if !IsCollection(predicates) {
    10  		panic("Predicates parameter must be an iteratee")
    11  	}
    12  
    13  	predicatesValue := reflect.ValueOf(predicates)
    14  	inputValue := reflect.ValueOf(value)
    15  
    16  	for i := 0; i < predicatesValue.Len(); i++ {
    17  		funcValue := predicatesValue.Index(i)
    18  		if !IsFunction(funcValue.Interface()) {
    19  			panic("Got non function as predicate")
    20  		}
    21  
    22  		funcType := funcValue.Type()
    23  		if !IsPredicate(funcValue.Interface()) {
    24  			panic("Predicate function must have 1 parameter and must return boolean")
    25  		}
    26  
    27  		if !inputValue.Type().ConvertibleTo(funcType.In(0)) {
    28  			panic("Given value is not compatible with type of parameter for the predicate.")
    29  		}
    30  		if result := funcValue.Call([]reflect.Value{inputValue}); wantedAnswer == result[0].Bool() {
    31  			return wantedAnswer
    32  		}
    33  	}
    34  
    35  	return !wantedAnswer
    36  }
    37  
    38  // AnyPredicates gets a value and a series of predicates, and return true if at least one of the predicates
    39  // is true.
    40  func AnyPredicates(value interface{}, predicates interface{}) bool {
    41  	return predicatesImpl(value, true, predicates)
    42  }
    43  
    44  // AllPredicates gets a value and a series of predicates, and return true if all of the predicates are true.
    45  func AllPredicates(value interface{}, predicates interface{}) bool {
    46  	return predicatesImpl(value, false, predicates)
    47  }
    48  

View as plain text