From d231d9f572013cb5ba84683cbc1d1c37e46aeed0 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Thu, 9 Feb 2023 17:53:26 +0800 Subject: [PATCH] feat: add DropRightWhile --- slice/slice.go | 16 ++++++++++++++++ slice/slice_example_test.go | 23 +++++++++++++++++++++++ slice/slice_test.go | 21 +++++++++++++++++++++ 3 files changed, 60 insertions(+) diff --git a/slice/slice.go b/slice/slice.go index 3f1e89e..04e712f 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -610,6 +610,22 @@ func DropWhile[T any](slice []T, predicate func(item T) bool) []T { return append(result, slice[i:]...) } +// DropRightWhile drop n elements from the end of a slice while predicate function returns true. +// Play: todo +func DropRightWhile[T any](slice []T, predicate func(item T) bool) []T { + i := len(slice) - 1 + + for ; i >= 0; i-- { + if !predicate(slice[i]) { + break + } + } + + result := make([]T, 0, i+1) + + return append(result, slice[:i+1]...) +} + // InsertAt insert the value or other slice into slice at index. // Play: https://go.dev/play/p/hMLNxPEGJVE func InsertAt[T any](slice []T, index int, value any) []T { diff --git a/slice/slice_example_test.go b/slice/slice_example_test.go index ce1584d..faae325 100644 --- a/slice/slice_example_test.go +++ b/slice/slice_example_test.go @@ -527,6 +527,29 @@ func ExampleDropWhile() { // [1 2 3 4 5] } +func ExampleDropRightWhile() { + numbers := []int{1, 2, 3, 4, 5} + + result1 := DropRightWhile(numbers, func(n int) bool { + return n != 2 + }) + result2 := DropRightWhile(numbers, func(n int) bool { + return true + }) + result3 := DropRightWhile(numbers, func(n int) bool { + return n == 0 + }) + + fmt.Println(result1) + fmt.Println(result2) + fmt.Println(result3) + + // Output: + // [1 2] + // [] + // [1 2 3 4 5] +} + func ExampleInsertAt() { result1 := InsertAt([]string{"a", "b", "c"}, 0, "1") result2 := InsertAt([]string{"a", "b", "c"}, 1, "1") diff --git a/slice/slice_test.go b/slice/slice_test.go index 4307e53..33b1d11 100644 --- a/slice/slice_test.go +++ b/slice/slice_test.go @@ -427,6 +427,27 @@ func TestDropWhile(t *testing.T) { assert.Equal([]int{1, 2, 3, 4, 5}, r3) } +func TestDropRightWhile(t *testing.T) { + assert := internal.NewAssert(t, "TestDropRightWhile") + + numbers := []int{1, 2, 3, 4, 5} + + r1 := DropRightWhile(numbers, func(n int) bool { + return n != 2 + }) + assert.Equal([]int{1, 2}, r1) + + r2 := DropRightWhile(numbers, func(n int) bool { + return true + }) + assert.Equal([]int{}, r2) + + r3 := DropRightWhile(numbers, func(n int) bool { + return n == 0 + }) + assert.Equal([]int{1, 2, 3, 4, 5}, r3) +} + func TestInsertAt(t *testing.T) { assert := internal.NewAssert(t, "TestInsertAt")