-
Notifications
You must be signed in to change notification settings - Fork 0
/
slice.go
66 lines (56 loc) · 1.43 KB
/
slice.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package golist
func validateSlicingArgs(listLen, start, stop int) (int, error) {
if start > listLen || stop > listLen {
return stop, ErrIndexOutOfRange
} else if start < 0 || stop < -1 {
return stop, ErrIndexOutOfRange
} else if stop == -1 {
stop = listLen
return stop, nil
} else {
return stop, nil
}
}
// Slice a list. similar to []int{1,2,3,4}[start:stop]
func (arr *List) Slice(start int, stop int) (*List, error) {
switch list := arr.list.(type) {
case []int:
stop, err := validateSlicingArgs(len(list), start, stop)
if err != nil {
return nil, err
}
return NewList(list[start:stop]), nil
case []int32:
stop, err := validateSlicingArgs(len(list), start, stop)
if err != nil {
return nil, err
}
return NewList(list[start:stop]), nil
case []int64:
stop, err := validateSlicingArgs(len(list), start, stop)
if err != nil {
return nil, err
}
return NewList(list[start:stop]), nil
case []float32:
stop, err := validateSlicingArgs(len(list), start, stop)
if err != nil {
return nil, err
}
return NewList(list[start:stop]), nil
case []float64:
stop, err := validateSlicingArgs(len(list), start, stop)
if err != nil {
return nil, err
}
return NewList(list[start:stop]), nil
case []string:
stop, err := validateSlicingArgs(len(list), start, stop)
if err != nil {
return nil, err
}
return NewList(list[start:stop]), nil
default:
return nil, ErrTypeNotsupported
}
}