1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add DropRightWhile

This commit is contained in:
dudaodong
2023-02-09 17:53:26 +08:00
parent 97447d058e
commit d231d9f572
3 changed files with 60 additions and 0 deletions

View File

@@ -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 {

View File

@@ -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")

View File

@@ -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")