-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathit.go
75 lines (65 loc) · 1.7 KB
/
it.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
// Copyright 2016 Andreas Pannewitz. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package do
// ===========================================================================
// It represents some action: do.It.
//
// The null value is useful: its Do() never does anything: it's a nop.
type It func()
// Do applies It iff It is not nil.
func (it *It) Do() {
if *it != nil {
(*it)()
}
}
// ===========================================================================
// ItJoin returns a closure around given fs.
//
// Iff there are no fs, nil is returned, and
// iff there is only one fs, this single fs is returned.
//
// Evaluate the returned function
// by invoking its Do() or
// by invoking it directly, iff not nil.
func ItJoin(fs ...It) It {
switch len(fs) {
case 0:
return nil
case 1:
return fs[0]
default:
return func() {
for _, f := range fs {
(&f).Do()
}
}
}
}
// ===========================================================================
// Set sets all its as the new It action
// when the returned Option is applied.
func (it *It) Set(its ...It) Option {
return func(any interface{}) Opt {
prev := *it
*it = ItJoin(its...)
return func() Opt {
return (*it).Set(prev)(any)
}
}
}
// Add appends all its to the existing It action
// when the returned Option is applied.
func (it *It) Add(its ...It) Option {
if it == nil || *it == nil {
return (*it).Set(its...)
}
return func(any interface{}) Opt {
prev := *it
*it = ItJoin(append([]It{prev}, its...)...)
return func() Opt {
return (*it).Set(prev)(any)
}
}
}
// ===========================================================================