Skip to content

Commit a88d4fa

Browse files
committed
add funcs CoalesceStrategy and FirstStrategy
1 parent 48296d2 commit a88d4fa

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

Diff for: backoff/strategy.go

+21
Original file line numberDiff line numberDiff line change
@@ -98,3 +98,24 @@ func WithTransforms(s Strategy, transforms ...linger.DurationTransform) Strategy
9898
return d
9999
}
100100
}
101+
102+
// CoalesceStrategy returns a strategy that iterates over the given strategies
103+
// and runs them, returning the first positive duration.
104+
func CoalesceStrategy(strategies ...Strategy) Strategy {
105+
return FirstStrategy(linger.Positive, strategies...)
106+
}
107+
108+
// FirstStrategy returns a strategy that iterates over the given strategies
109+
// and runs them, returning the first duration which satisfies the predicate.
110+
// Return zero if no duration satisfies the predicate.
111+
func FirstStrategy(p linger.DurationPredicate, strategies ...Strategy) Strategy {
112+
return func(e error, n uint) time.Duration {
113+
for _, s := range strategies {
114+
d := s(e, n)
115+
if p(d) {
116+
return d
117+
}
118+
}
119+
return 0
120+
}
121+
}

Diff for: backoff/strategy_test.go

+38
Original file line numberDiff line numberDiff line change
@@ -108,3 +108,41 @@ var _ = Describe("func WithTransform()", func() {
108108
Expect(s(nil, 2)).To(Equal(25 * time.Second))
109109
})
110110
})
111+
112+
var _ = Describe("func CoalesceStrategy()", func() {
113+
It("returns a strategy that yields the first positive duration", func() {
114+
115+
stgyOne := func(_ error, n uint) time.Duration {
116+
if n == 1 {
117+
return 6 * time.Second
118+
}
119+
return 0
120+
}
121+
122+
stgyTwo := func(_ error, n uint) time.Duration {
123+
if n == 2 {
124+
return 9 * time.Second
125+
}
126+
return 0
127+
}
128+
129+
s := CoalesceStrategy(
130+
stgyOne,
131+
stgyTwo,
132+
)
133+
134+
sC := CoalesceStrategy(
135+
s,
136+
Constant(3*time.Second),
137+
)
138+
139+
Expect(s(nil, 0)).To(Equal(0 * time.Second))
140+
Expect(s(nil, 1)).To(Equal(6 * time.Second))
141+
Expect(s(nil, 2)).To(Equal(9 * time.Second))
142+
143+
Expect(sC(nil, 0)).To(Equal(3 * time.Second))
144+
Expect(sC(nil, 1)).To(Equal(6 * time.Second))
145+
Expect(sC(nil, 2)).To(Equal(9 * time.Second))
146+
147+
})
148+
})

0 commit comments

Comments
 (0)