-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
75 lines (64 loc) · 1.76 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
package main
import "fmt"
// Condition represents a condition that needs to be satisfied.
type Condition func(factors map[string]interface{}) bool
// Action represents an action to be taken when conditions are met.
type Action func(factors map[string]interface{})
// Rule represents a rule with its conditions and action.
type Rule struct {
Conditions []Condition
Action Action
}
// RuleEngine represents the rule engine.
type RuleEngine struct {
Rules []Rule
}
// NewRuleEngine creates a new RuleEngine instance.
func NewRuleEngine() *RuleEngine {
return &RuleEngine{}
}
// AddRule adds a rule to the RuleEngine.
func (re *RuleEngine) AddRule(conditions []Condition, action Action) {
re.Rules = append(re.Rules, Rule{Conditions: conditions, Action: action})
}
// EvaluateRules evaluates the rules against the given factors.
func (re *RuleEngine) EvaluateRules(factors map[string]interface{}) {
for _, rule := range re.Rules {
conditionsMet := true
for _, cond := range rule.Conditions {
if !cond(factors) {
conditionsMet = false
break
}
}
if conditionsMet {
rule.Action(factors)
}
}
}
func main() {
ruleEngine := NewRuleEngine()
ruleEngine.AddRule(
[]Condition{
func(factors map[string]interface{}) bool {
temperature, ok := factors["temperature"].(float64)
return ok && temperature > 30
},
func(factors map[string]interface{}) bool {
temperature, ok := factors["temperature"].(float64)
return ok && temperature < 35
},
},
func(factors map[string]interface{}) {
fmt.Println("It's hot! Turn on the AC.")
},
)
//factors := map[string]interface{}{
// "temperature": 32.0,
//}
factors2 := map[string]interface{}{
"temperature": 32.0,
}
//ruleEngine.EvaluateRules(factors)
ruleEngine.EvaluateRules(factors2)
}