diff --git a/slice/slice.go b/slice/slice.go index 9585941..fb91854 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -421,6 +421,17 @@ func ForEach[T any](slice []T, iteratee func(index int, item T)) { } } +// ForEachWithBreak iterates over elements of slice and invokes function for each element, +// when iteratee return true, will break the for each loop. +func ForEachWithBreak[T any](slice []T, iteratee func(index int, item T) bool) { +loop: + for i, v := range slice { + if !iteratee(i, v) { + break loop + } + } +} + // Map creates an slice of values by running each element of slice thru iteratee function. // Play: https://go.dev/play/p/biaTefqPquw func Map[T any, U any](slice []T, iteratee func(index int, item T) U) []U { diff --git a/slice/slice_example_test.go b/slice/slice_example_test.go index 0adf1ae..02fbd4b 100644 --- a/slice/slice_example_test.go +++ b/slice/slice_example_test.go @@ -379,6 +379,25 @@ func ExampleForEach() { // [2 3 4] } +func ExampleForEachWithBreak() { + numbers := []int{1, 2, 3, 4, 5} + + var sum int + + ForEachWithBreak(numbers, func(_, n int) bool { + if n > 3 { + return false + } + sum += n + return true + }) + + fmt.Println(sum) + + // Output: + // 6 +} + func ExampleMap() { nums := []int{1, 2, 3} diff --git a/slice/slice_test.go b/slice/slice_test.go index 6dc1e82..f4af1dc 100644 --- a/slice/slice_test.go +++ b/slice/slice_test.go @@ -307,6 +307,23 @@ func TestForEach(t *testing.T) { assert.Equal(expected, numbersAddTwo) } +func TestForEachWithBreak(t *testing.T) { + numbers := []int{1, 2, 3, 4, 5} + + var sum int + + ForEachWithBreak(numbers, func(_, n int) bool { + if n > 3 { + return false + } + sum += n + return true + }) + + assert := internal.NewAssert(t, "TestForEach") + assert.Equal(6, sum) +} + func TestMap(t *testing.T) { nums := []int{1, 2, 3, 4} multiplyTwo := func(i, num int) int {