-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswitch.go
More file actions
42 lines (36 loc) · 895 Bytes
/
switch.go
File metadata and controls
42 lines (36 loc) · 895 Bytes
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
package fun
type switchCase[T comparable, R any] struct {
predicate T
result R
done bool
}
// Switch is a pure functional switch/case/default statement.
func Switch[R any, T comparable](predicate T, defVal R) *switchCase[T, R] {
return &switchCase[T, R]{
predicate: predicate,
result: defVal,
done: false,
}
}
// SwitchZero is a pure functional switch/case/default statement with default zero value.
func SwitchZero[R any, T comparable](predicate T) *switchCase[T, R] {
return Switch(predicate, Zero[R]())
}
func (s *switchCase[T, R]) Case(result R, val T, vals ...T) *switchCase[T, R] {
if !s.done && s.predicate == val {
s.result = result
s.done = true
return s
}
for _, val := range vals {
if !s.done && s.predicate == val {
s.result = result
s.done = true
break
}
}
return s
}
func (s *switchCase[T, R]) End() R {
return s.result
}