-
Notifications
You must be signed in to change notification settings - Fork 12
/
memoizers_test.go
93 lines (77 loc) · 1.71 KB
/
memoizers_test.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main_test
import . "github.com/onsi/ginkgo"
// Memoization method strongly influenced by https://github.com/d11wtq/node-memo-is
type StringMemoizer interface {
Get() string
Is(func() string)
}
type StringMapMemoizer interface {
Get() map[string]string
Is(func() map[string]string)
}
type stringMemoizer struct {
value string
stack []func() string
invoked bool
}
type stringMapMemoizer struct {
value map[string]string
stack []func() map[string]string
invoked bool
}
func NewStringMemoizer(cb func() string) StringMemoizer {
memo := &stringMemoizer{
stack: []func() string{},
invoked: false,
}
memo.Is(cb)
return memo
}
func NewStringMapMemoizer(cb func() map[string]string) StringMapMemoizer {
memo := &stringMapMemoizer{
stack: []func() map[string]string{},
invoked: false,
}
memo.Is(cb)
return memo
}
func (s *stringMemoizer) Is(cb func() string) {
BeforeEach(func() {
s.stack = append(s.stack, cb)
})
AfterEach(func() {
s.invoked = false
s.value = ""
s.stack = s.stack[:len(s.stack)-1]
})
}
func (s *stringMapMemoizer) Is(cb func() map[string]string) {
BeforeEach(func() {
s.stack = append(s.stack, cb)
})
AfterEach(func() {
s.invoked = false
s.value = nil
s.stack = s.stack[:len(s.stack)-1]
})
}
func (s *stringMemoizer) Get() string {
if len(s.stack) == 0 {
Fail("Memoized function called outside test example scope")
}
if !s.invoked {
s.value = s.stack[len(s.stack)-1]()
s.invoked = true
}
return s.value
}
func (s *stringMapMemoizer) Get() map[string]string {
if len(s.stack) == 0 {
Fail("Memoized function called outside test example scope")
}
if !s.invoked {
s.value = s.stack[len(s.stack)-1]()
s.invoked = true
}
return s.value
}