Skip to content

Commit 40a121e

Browse files
committed
feat: drop support from ending
1 parent d4dd7bd commit 40a121e

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

slice/drop.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
package slice
22

33
// Drop
4-
// Creates a slice of array with n elements dropped from the beginning.
4+
// Creates a slice of array with n elements dropped from the beginning while n >=0 and the endding while n < 0.
55
func Drop[T any](array []T, n int) (result []T) {
66
length := len(array)
7+
if n < 0 {
8+
n = length + n
9+
}
710
if length <= n || n < 0 {
811
return array
912
}

slice/drop_test.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,20 @@ func TestDrop(t *testing.T) {
2424
if result4[len(result4)-1] != "bar" {
2525
t.Error("drop end error result: ", result4)
2626
}
27+
28+
result5 := Drop(arr3, -1)
29+
if result5[len(result5)-1] != "bar" {
30+
t.Error("drop -1 error result: ", result5)
31+
}
2732
}
2833

2934
func ExampleDrop() {
3035
array := []int{1, 3, 4, 5}
31-
3236
fmt.Println(Drop(array, 1))
37+
38+
array2 := []string{"start", "foo", "bar", "end"}
39+
fmt.Println(Drop(array2, -1))
3340
// Output:
34-
//[1 4 5]
41+
// [1 4 5]
42+
// [start foo bar]
3543
}

0 commit comments

Comments
 (0)