Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/vulcand/predicate
Library for creating predicate mini-languages in Go
https://github.com/vulcand/predicate
go golang mini-language predicate
Last synced: 4 days ago
JSON representation
Library for creating predicate mini-languages in Go
- Host: GitHub
- URL: https://github.com/vulcand/predicate
- Owner: vulcand
- License: apache-2.0
- Created: 2014-10-19T02:29:19.000Z (about 10 years ago)
- Default Branch: master
- Last Pushed: 2024-12-12T00:26:08.000Z (22 days ago)
- Last Synced: 2024-12-23T04:00:38.359Z (11 days ago)
- Topics: go, golang, mini-language, predicate
- Language: Go
- Homepage: https://pkg.go.dev/github.com/vulcand/predicate#section-readme
- Size: 43 KB
- Stars: 96
- Watchers: 23
- Forks: 17
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
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:
```go
package mainimport (
"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
}
```