From 3e019522c7b5f1fb479ee88e162d803a5c221e09 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Wed, 15 Mar 2023 14:42:22 +0800 Subject: [PATCH] doc: add doc for ForEachWithBreak --- docs/slice.md | 40 ++++++++++++++++++++++++++++++++++++++++ docs/slice_zh-CN.md | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) diff --git a/docs/slice.md b/docs/slice.md index 0526176..a3ad7ac 100644 --- a/docs/slice.md +++ b/docs/slice.md @@ -48,6 +48,7 @@ import ( - [Flatten](#Flatten) - [FlattenDeep](#FlattenDeep) - [ForEach](#ForEach) +- [ForEachWithBreak](#ForEachWithBreak) - [GroupBy](#GroupBy) - [GroupWith](#GroupWith) - [IntSlicedeprecated](#IntSlice) @@ -1001,6 +1002,45 @@ func main() { } ``` + +### ForEachWithBreak + +

Iterates over elements of slice and invokes function for each element, when iteratee return true, will break the for each loop.

+ +Signature: + +```go +func ForEachWithBreak[T any](slice []T, iteratee func(index int, item T) bool) +``` + +Example: + +```go +import ( + "fmt" + "github.com/duke-git/lancet/v2/slice" +) + +func main() { + numbers := []int{1, 2, 3, 4, 5} + + var sum int + + slice.ForEachWithBreak(numbers, func(_, n int) bool { + if n > 3 { + return false + } + sum += n + return true + }) + + fmt.Println(sum) + + // Output: + // 6 +} +``` + ### GroupBy

Iterates over elements of the slice, each element will be group by criteria, returns two slices.

diff --git a/docs/slice_zh-CN.md b/docs/slice_zh-CN.md index 45ff24b..3230e6e 100644 --- a/docs/slice_zh-CN.md +++ b/docs/slice_zh-CN.md @@ -48,6 +48,7 @@ import ( - [Flatten](#Flatten) - [FlattenDeep](#FlattenDeep) - [ForEach](#ForEach) +- [ForEachWithBreak](#ForEachWithBreak) - [GroupBy](#GroupBy) - [GroupWith](#GroupWith) - [IntSlicedeprecated](#IntSlice) @@ -1003,6 +1004,46 @@ func main() { } ``` + +### ForEachWithBreak + +

遍历切片的元素并为每个元素调用iteratee函数,当iteratee函数返回false时,终止遍历。

+ +函数签名: + +```go +func ForEachWithBreak[T any](slice []T, iteratee func(index int, item T) bool) +``` + +示例: + +```go +import ( + "fmt" + "github.com/duke-git/lancet/v2/slice" +) + +func main() { + numbers := []int{1, 2, 3, 4, 5} + + var sum int + + slice.ForEachWithBreak(numbers, func(_, n int) bool { + if n > 3 { + return false + } + sum += n + return true + }) + + fmt.Println(sum) + + // Output: + // 6 +} +``` + + ### GroupBy

迭代切片的元素,每个元素将按条件分组,返回两个切片