Codebase list golang-github-vbauerster-mpb / f0a0ad1
add Conditional and Predicative helpers Vladimir Bauer 3 years ago
1 changed file(s) with 39 addition(s) and 11 deletion(s). Raw diff Collapse all Expand all
00 package decor
11
2 // OnPredicate returns decorator if predicate evaluates to true.
2 // OnCondition applies decorator only if a condition is true.
3 //
4 // `decorator` Decorator
5 //
6 // `cond` bool
7 //
8 func OnCondition(decorator Decorator, cond bool) Decorator {
9 return Conditional(cond, decorator, nil)
10 }
11
12 // OnPredicate applies decorator only if a predicate evaluates to true.
313 //
414 // `decorator` Decorator
515 //
616 // `predicate` func() bool
717 //
818 func OnPredicate(decorator Decorator, predicate func() bool) Decorator {
9 if predicate() {
10 return decorator
11 }
12 return nil
19 return Predicative(predicate, decorator, nil)
1320 }
1421
15 // OnCondition returns decorator if condition is true.
16 //
17 // `decorator` Decorator
22 // Conditional returns decorator `a` if condition is true, otherwise
23 // decorator `b`.
1824 //
1925 // `cond` bool
2026 //
21 func OnCondition(decorator Decorator, cond bool) Decorator {
27 // `a` Decorator
28 //
29 // `b` Decorator
30 //
31 func Conditional(cond bool, a, b Decorator) Decorator {
2232 if cond {
23 return decorator
33 return a
34 } else {
35 return b
2436 }
25 return nil
2637 }
38
39 // Predicative returns decorator `a` if predicate evaluates to true,
40 // otherwise decorator `b`.
41 //
42 // `predicate` func() bool
43 //
44 // `a` Decorator
45 //
46 // `b` Decorator
47 //
48 func Predicative(predicate func() bool, a, b Decorator) Decorator {
49 if predicate() {
50 return a
51 } else {
52 return b
53 }
54 }