# README
Predicate
Predicate package used to create interpreted mini languages with Go syntax - mostly to define various predicates for configuration, e.g.
Latency() > 40 || ErrorRate() > 0.5.
Here's an example of fully functional predicate language to deal with division remainders:
package main
import (
"log"
"github.com/vulcand/predicate"
)
// takes number and returns true or false
type numberPredicate func(v int) bool
// Converts one number to another
type numberMapper func(v int) int
// Function that creates predicate to test if the remainder is 0
func divisibleBy(divisor int) numberPredicate {
return func(v int) bool {
return v%divisor == 0
}
}
// Function - logical operator AND that combines predicates
func numberAND(a, b numberPredicate) numberPredicate {
return func(v int) bool {
return a(v) && b(v)
}
}
func main(){
// Create a new parser and define the supported operators and methods
p, err := predicate.NewParser(predicate.Def{
Operators: predicate.Operators{
AND: numberAND,
},
Functions: map[string]interface{}{
"DivisibleBy": divisibleBy,
},
})
pr, err := p.Parse("DivisibleBy(2) && DivisibleBy(3)")
if err != nil {
log.Fatalf("Error: %v", err)
}
fmt.Println(pr.(numberPredicate)(2)) // false
fmt.Println(pr.(numberPredicate)(3)) // false
fmt.Println(pr.(numberPredicate)(6)) // true
}
# Packages
Package builder is used to construct predicate expressions using builder functions.
# Functions
And is a boolean predicate that calls two boolean predicates and returns result of && operation on their return values.
Contains checks if string slice contains a string Contains([]string{"a", "b"}, "b") -> true.
Equals can compare complex objects, e.g.
GetFieldByTag returns a field from the object based on the tag.
GetStringMapValue is a helper function that returns property from map[string]string or map[string][]string the function returns empty value in case if key not found In case if map is nil, returns empty value as well.
No description provided by the author
Not is a boolean predicate that calls a boolean predicate and returns negated result.
Or is a boolean predicate that calls two boolean predicates and returns result of || operation on their return values.
# Interfaces
Parser takes the string with expression and calls the operators and functions.
# Type aliases
BoolPredicate is a function without arguments that returns boolean value when called.
GetIdentifierFn function returns identifier based on selector e.g.
GetPropertyFn returns property from a mapVal by key keyVal.