From c6f0028dc2c42784b0caeafae848d5a4580e150f Mon Sep 17 00:00:00 2001 From: sia Date: Tue, 2 Jul 2024 12:33:43 +0800 Subject: [PATCH] add example and test code --- slice_example_test.go | 14 ++++++++++++++ slice_test.go | 23 +++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/slice_example_test.go b/slice_example_test.go index 1ee90ced..8dea28b6 100644 --- a/slice_example_test.go +++ b/slice_example_test.go @@ -88,7 +88,21 @@ func ExampleForEach() { // 3 // 4 } +func ExampleForEachCondition() { + list := []int64{1, 2, -math.MaxInt, 4} + ForEachCondition(list, func(x int64, _ int) bool { + if x < 0 { + return false + } + fmt.Println(x) + return true + }) + + // Output: + // 1 + // 2 +} func ExampleTimes() { result := Times(3, func(i int) string { return strconv.FormatInt(int64(i), 10) diff --git a/slice_test.go b/slice_test.go index 0917e171..7c8a8316 100644 --- a/slice_test.go +++ b/slice_test.go @@ -157,6 +157,29 @@ func TestForEach(t *testing.T) { is.IsIncreasing(callParams2) } +func TestForEachCondition(t *testing.T) { + t.Parallel() + is := assert.New(t) + + // check of callback is called for every element and in proper order + + var callParams1 []string + var callParams2 []int + + ForEachCondition([]string{"a", "b", "c"}, func(item string, i int) bool { + if item == "c" { + return false + } + callParams1 = append(callParams1, item) + callParams2 = append(callParams2, i) + return true + }) + + is.ElementsMatch([]string{"a", "b"}, callParams1) + is.ElementsMatch([]int{0, 1}, callParams2) + is.IsIncreasing(callParams2) +} + func TestUniq(t *testing.T) { t.Parallel() is := assert.New(t)