-
Notifications
You must be signed in to change notification settings - Fork 1
/
condition.go
56 lines (48 loc) · 1.29 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
package ternary
import "reflect"
// Condition represents boolean flag itself.
type Condition bool
// If construct Condition struct, to prepare to return anything.
func If(flag bool) Condition {
return Condition(flag)
}
// Zero ...
func Zero(i interface{}) Condition {
v := reflect.ValueOf(i)
t := v.Type()
return Condition(v.Interface() == reflect.Zero(t).Interface())
}
// Int concludes to return `int` type value, according to given condition.
func (cond Condition) Int(yes, no int) int {
if cond {
return yes
}
return no
}
// String concludes to return `string` type value, according to given condition.
func (cond Condition) String(yes, no string) string {
if cond {
return yes
}
return no
}
// Interface concludes to return `string` type value, according to given condition.
func (cond Condition) Interface(yes, no interface{}) interface{} {
if cond {
return yes
}
return no
}
// Put provides put-func to place key-value on map following.
//
// It allows putting key-value on given target if flag is true,
// or do nothing otherwise.
// It means the given key will not exist on the target map.
func (cond Condition) Put(key string, value interface{}) func(map[string]interface{}) {
return func(target map[string]interface{}) {
if cond {
target[key] = value
}
// else, do nothing
}
}