-
Notifications
You must be signed in to change notification settings - Fork 1
/
dropRight.go
47 lines (36 loc) · 1.01 KB
/
dropRight.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package array
import (
"reflect"
"github.com/warriors-vn/go-dash/constants"
)
// DropRight returns a new array with `num` elements dropped from the end.
// The function accepts an array of any type (interface{}) and an optional number `num` of elements to Drop.
// It returns a new array with the specified number of elements removed from the end.
func DropRight(array interface{}, num ...int) (interface{}, error) {
arrValue, n := reflect.ValueOf(array), 0
if arrValue.Kind() != reflect.Slice && arrValue.Kind() != reflect.Array {
return nil, constants.ErrNotSlice
}
if num != nil {
n = num[0]
} else {
return array, nil
}
if n == 0 {
return array, nil
}
if n < 0 {
return nil, constants.ErrParamLessThanZero
}
if arrValue.Len() == 0 {
return array, nil
}
result := reflect.MakeSlice(arrValue.Type(), 0, 0)
if n >= arrValue.Len() {
return result.Interface(), nil
}
for i := 0; i < arrValue.Len()-n; i++ {
result = reflect.Append(result, arrValue.Index(i))
}
return result.Interface(), nil
}