-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpipeline_conditional_step_builder.go
48 lines (41 loc) · 1.45 KB
/
pipeline_conditional_step_builder.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
package pipeline
type ConditionalStepBuilder[K any] struct {
condition func(context K) bool
trueSteps []Step[K]
falseSteps []Step[K]
}
func (b *ConditionalStepBuilder[K]) Condition(condition func(context K) bool) *ConditionalStepBuilder[K] {
b.condition = condition
return b
}
func (b *ConditionalStepBuilder[K]) IfTrue(steps ...Step[K]) *ConditionalStepBuilder[K] {
b.trueSteps = steps
return b
}
func (b *ConditionalStepBuilder[K]) IfFalse(steps ...Step[K]) *ConditionalStepBuilder[K] {
b.falseSteps = steps
return b
}
func (b *ConditionalStepBuilder[K]) Build() func(next StepDelegate[K]) StepDelegate[K] {
return func(next StepDelegate[K]) StepDelegate[K] {
truePipeline := Builder[K]{steps: b.toStepDelegates(b.trueSteps)}.Build()
falsePipeline := Builder[K]{steps: b.toStepDelegates(b.falseSteps)}.Build()
return func(context K) error {
return ConditionalStep[K]{b.condition, truePipeline, falsePipeline}.Execute(context, next)
}
}
}
func (b *ConditionalStepBuilder[K]) toStepDelegates(steps []Step[K]) []func(next StepDelegate[K]) StepDelegate[K] {
stepDelegates := make([]func(next StepDelegate[K]) StepDelegate[K], len(steps))
for i, step := range steps {
stepDelegates[i] = func(next StepDelegate[K]) StepDelegate[K] {
return func(context K) error {
return step.Execute(context, next)
}
}
}
return stepDelegates
}
func NewConditionalStepBuilder[K any]() *ConditionalStepBuilder[K] {
return &ConditionalStepBuilder[K]{}
}