-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
88 lines (76 loc) · 1.85 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"log"
"github.com/spy16/slurp"
"github.com/spy16/slurp/builtin"
"github.com/spy16/slurp/core"
)
func main() {
// Accept business rules from file, command-line, http request etc.
// These rules can change as per business requirements and your
// application doesn't have to change.
ruleSrc := `(and (regular-user? current-user)
(not-blacklisted? current-user))`
shouldDiscount, err := runDiscountingRule(ruleSrc, "bob")
if err != nil {
panic(err)
}
if shouldDiscount {
// apply discount for the order
log.Printf("applying discount")
} else {
// don't apply discount
log.Printf("not applying discount")
}
}
func runDiscountingRule(rule string, user string) (bool, error) {
// Define and expose your rules which ideally should have no
// side effects.
globals := map[string]core.Any{
"and": slurp.Func("and", and),
"or": slurp.Func("or", or),
"regular-user?": slurp.Func("isRegularUser", isRegularUser),
"minimum-cart-price?": slurp.Func("isMinCartPrice", isMinCartPrice),
"not-blacklisted?": slurp.Func("isNotBlacklisted", isNotBlacklisted),
"current-user": user,
}
ins := slurp.New()
_ = ins.Bind(globals)
shouldDiscount, err := ins.EvalStr(rule)
return builtin.IsTruthy(shouldDiscount), err
}
func isNotBlacklisted(user string) bool {
return user != "joe"
}
func isMinCartPrice(price float64) bool {
return price >= 100
}
func isRegularUser(user string) bool {
return user == "bob"
}
func and(rest ...bool) bool {
if len(rest) == 0 {
return true
}
result := rest[0]
for _, r := range rest {
result = result && r
if !result {
return false
}
}
return true
}
func or(rest ...bool) bool {
if len(rest) == 0 {
return true
}
result := rest[0]
for _, r := range rest {
if result {
return true
}
result = result || r
}
return false
}