-
Notifications
You must be signed in to change notification settings - Fork 2
/
condition.go
119 lines (90 loc) · 1.75 KB
/
condition.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package sugar
func Ternary[T any](condition bool, ifOutput T, elseOutput T) T {
if condition {
return ifOutput
}
return elseOutput
}
type IfElse[T any] struct {
Result T
Ok bool
}
func If[T any](condition bool, result T) *IfElse[T] {
if condition {
return &IfElse[T]{result, true}
}
var t T
return &IfElse[T]{t, false}
}
func IfFn[T any](condition bool, resultFn func() T) *IfElse[T] {
if condition {
return &IfElse[T]{resultFn(), true}
}
var t T
return &IfElse[T]{t, false}
}
func (i *IfElse[T]) ElseIf(condition bool, result T) *IfElse[T] {
if condition && !i.Ok {
i.Result = result
i.Ok = true
}
return i
}
func (i *IfElse[T]) ElseIfFn(condition bool, resultFn func() T) *IfElse[T] {
if condition && !i.Ok {
i.Result = resultFn()
i.Ok = true
}
return i
}
func (i *IfElse[T]) Else(result T) T {
if i.Ok {
return i.Result
}
return result
}
func (i *IfElse[T]) ElseFn(resultFn func() T) T {
if i.Ok {
return i.Result
}
return resultFn()
}
type SwitchCase[T comparable, R any] struct {
Predicate T
Result R
Ok bool
}
func Switch[T comparable, R any](predicate T) *SwitchCase[T, R] {
var result R
return &SwitchCase[T, R]{
predicate,
result,
false,
}
}
func (s *SwitchCase[T, R]) Case(value T, result R) *SwitchCase[T, R] {
if !s.Ok && s.Predicate == value {
s.Result = result
s.Ok = true
}
return s
}
func (s *SwitchCase[T, R]) CaseFn(value T, resultFn func() R) *SwitchCase[T, R] {
if !s.Ok && value == s.Predicate {
s.Result = resultFn()
s.Ok = true
}
return s
}
func (s *SwitchCase[T, R]) Default(result R) R {
if !s.Ok {
s.Result = result
}
return s.Result
}
func (s *SwitchCase[T, R]) DefaultFn(resultFn func() R) R {
if !s.Ok {
s.Result = resultFn()
}
return s.Result
}