mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-17 19:22:28 +08:00
feat: add ForEachWithBreak support break for each loop
This commit is contained in:
@@ -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.
|
// Map creates an slice of values by running each element of slice thru iteratee function.
|
||||||
// Play: https://go.dev/play/p/biaTefqPquw
|
// Play: https://go.dev/play/p/biaTefqPquw
|
||||||
func Map[T any, U any](slice []T, iteratee func(index int, item T) U) []U {
|
func Map[T any, U any](slice []T, iteratee func(index int, item T) U) []U {
|
||||||
|
|||||||
@@ -379,6 +379,25 @@ func ExampleForEach() {
|
|||||||
// [2 3 4]
|
// [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() {
|
func ExampleMap() {
|
||||||
nums := []int{1, 2, 3}
|
nums := []int{1, 2, 3}
|
||||||
|
|
||||||
|
|||||||
@@ -307,6 +307,23 @@ func TestForEach(t *testing.T) {
|
|||||||
assert.Equal(expected, numbersAddTwo)
|
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) {
|
func TestMap(t *testing.T) {
|
||||||
nums := []int{1, 2, 3, 4}
|
nums := []int{1, 2, 3, 4}
|
||||||
multiplyTwo := func(i, num int) int {
|
multiplyTwo := func(i, num int) int {
|
||||||
|
|||||||
Reference in New Issue
Block a user