Skip to content

Commit cbfd1c6

Browse files
authored
add ForEachCondition implement (#485)
* add ForEachCondition implement * add example and test code * rename ForEachCondition() to ForEachWhile() * update test and example code * rename ExampleForForEachWhile() to ExampleForEachWhile()
1 parent 0f4679b commit cbfd1c6

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed

slice.go

+10
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,16 @@ func ForEach[T any](collection []T, iteratee func(item T, index int)) {
9494
}
9595
}
9696

97+
// ForEachWhile iterates over elements of collection and invokes iteratee for each element
98+
// collection return value decide to continue or break ,just like do while()
99+
func ForEachWhile[T any](collection []T, iteratee func(item T, index int) (goon bool)) {
100+
for i := range collection {
101+
if !iteratee(collection[i], i) {
102+
break
103+
}
104+
}
105+
}
106+
97107
// Times invokes the iteratee n times, returning an array of the results of each invocation.
98108
// The iteratee is invoked with index as argument.
99109
// Play: https://go.dev/play/p/vgQj3Glr6lT

slice_example_test.go

+14
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,21 @@ func ExampleForEach() {
8888
// 3
8989
// 4
9090
}
91+
func ExampleForEachWhile() {
92+
list := []int64{1, 2, -math.MaxInt, 4}
9193

94+
ForEachWhile(list, func(x int64, _ int) bool {
95+
if x < 0 {
96+
return false
97+
}
98+
fmt.Println(x)
99+
return true
100+
})
101+
102+
// Output:
103+
// 1
104+
// 2
105+
}
92106
func ExampleTimes() {
93107
result := Times(3, func(i int) string {
94108
return strconv.FormatInt(int64(i), 10)

slice_test.go

+23
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,29 @@ func TestForEach(t *testing.T) {
157157
is.IsIncreasing(callParams2)
158158
}
159159

160+
func TestForEachWhile(t *testing.T) {
161+
t.Parallel()
162+
is := assert.New(t)
163+
164+
// check of callback is called for every element and in proper order
165+
166+
var callParams1 []string
167+
var callParams2 []int
168+
169+
ForEachWhile([]string{"a", "b", "c"}, func(item string, i int) bool {
170+
if item == "c" {
171+
return false
172+
}
173+
callParams1 = append(callParams1, item)
174+
callParams2 = append(callParams2, i)
175+
return true
176+
})
177+
178+
is.ElementsMatch([]string{"a", "b"}, callParams1)
179+
is.ElementsMatch([]int{0, 1}, callParams2)
180+
is.IsIncreasing(callParams2)
181+
}
182+
160183
func TestUniq(t *testing.T) {
161184
t.Parallel()
162185
is := assert.New(t)

0 commit comments

Comments
 (0)