refactoring: inspect decorators
Vladimir Bauer
3 years ago
| 9 | 9 | // BarOption is a func option to alter default behavior of a bar. |
| 10 | 10 | type BarOption func(*bState) |
| 11 | 11 | |
| 12 | func skipNil(decorators []decor.Decorator) (filtered []decor.Decorator) { | |
| 13 | for _, d := range decorators { | |
| 14 | if d != nil { | |
| 15 | filtered = append(filtered, d) | |
| 12 | func inspect(decorators []decor.Decorator) (dest []decor.Decorator) { | |
| 13 | type mergeWrapper interface { | |
| 14 | MergeUnwrap() []decor.Decorator | |
| 15 | } | |
| 16 | for _, decorator := range decorators { | |
| 17 | if decorator == nil { | |
| 18 | continue | |
| 16 | 19 | } |
| 20 | if mw, ok := decorator.(mergeWrapper); ok { | |
| 21 | dest = append(dest, mw.MergeUnwrap()...) | |
| 22 | } | |
| 23 | dest = append(dest, decorator) | |
| 17 | 24 | } |
| 18 | 25 | return |
| 19 | 26 | } |
| 20 | 27 | |
| 21 | func (s *bState) addDecorators(dest *[]decor.Decorator, decorators ...decor.Decorator) { | |
| 22 | type mergeWrapper interface { | |
| 23 | MergeUnwrap() []decor.Decorator | |
| 24 | } | |
| 25 | for _, decorator := range decorators { | |
| 26 | if mw, ok := decorator.(mergeWrapper); ok { | |
| 27 | *dest = append(*dest, mw.MergeUnwrap()...) | |
| 28 | } | |
| 29 | *dest = append(*dest, decorator) | |
| 30 | } | |
| 31 | } | |
| 32 | ||
| 33 | 28 | // AppendDecorators let you inject decorators to the bar's right side. |
| 34 | 29 | func AppendDecorators(decorators ...decor.Decorator) BarOption { |
| 30 | decorators = inspect(decorators) | |
| 35 | 31 | return func(s *bState) { |
| 36 | s.addDecorators(&s.aDecorators, skipNil(decorators)...) | |
| 32 | s.aDecorators = decorators | |
| 37 | 33 | } |
| 38 | 34 | } |
| 39 | 35 | |
| 40 | 36 | // PrependDecorators let you inject decorators to the bar's left side. |
| 41 | 37 | func PrependDecorators(decorators ...decor.Decorator) BarOption { |
| 38 | decorators = inspect(decorators) | |
| 42 | 39 | return func(s *bState) { |
| 43 | s.addDecorators(&s.pDecorators, skipNil(decorators)...) | |
| 40 | s.pDecorators = decorators | |
| 44 | 41 | } |
| 45 | 42 | } |
| 46 | 43 |