forked from samber/lo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
condition.go
99 lines (79 loc) · 1.49 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
package lo
// Ternary is a 1 line if/else statement.
func Ternary[T any](condition bool, ifOutput T, elseOutput T) T {
if condition {
return ifOutput
}
return elseOutput
}
type ifElse[T any] struct {
result T
done bool
}
// If.
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}
}
// ElseIf.
func (i *ifElse[T]) ElseIf(condition bool, result T) *ifElse[T] {
if !i.done && condition {
i.result = result
i.done = true
}
return i
}
// Else.
func (i *ifElse[T]) Else(result T) T {
if i.done {
return i.result
}
return result
}
type switchCase[T comparable, R any] struct {
predicate T
result R
done bool
}
// Switch is a pure functional switch/case/default statement.
func Switch[T comparable, R any](predicate T) *switchCase[T, R] {
var result R
return &switchCase[T, R]{
predicate,
result,
false,
}
}
// Case.
func (s *switchCase[T, R]) Case(val T, result R) *switchCase[T, R] {
if !s.done && s.predicate == val {
s.result = result
s.done = true
}
return s
}
// CaseF.
func (s *switchCase[T, R]) CaseF(val T, cb func() R) *switchCase[T, R] {
if !s.done && s.predicate == val {
s.result = cb()
s.done = true
}
return s
}
// Default.
func (s *switchCase[T, R]) Default(result R) R {
if !s.done {
s.result = result
}
return s.result
}
// DefaultF.
func (s *switchCase[T, R]) DefaultF(cb func() R) R {
if !s.done {
s.result = cb()
}
return s.result
}