Skip to content

Commit da3b6e8

Browse files
committed
Add Slice function for range type
Crate a new range object by calculating start, stop, and step when slice is entered as argument to the __getitem__ function of the range Fixes #77
1 parent eb115a9 commit da3b6e8

File tree

1 file changed

+44
-2
lines changed

1 file changed

+44
-2
lines changed

py/range.go

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,12 +79,54 @@ func RangeNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error) {
7979
}
8080

8181
func (r *Range) M__getitem__(key Object) (Object, error) {
82+
length := r.Length
83+
if slice, ok := key.(*Slice); ok {
84+
length, err := length.GoInt()
85+
if err != nil {
86+
return nil, err
87+
}
88+
start, stop, step, sliceLength, err := slice.GetIndices(length)
89+
if err != nil {
90+
return nil, err
91+
}
92+
93+
if step == 0 {
94+
return nil, ExceptionNewf(ValueError, "slice step cannot be zero")
95+
}
96+
if start < 0 {
97+
start += length
98+
}
99+
if stop < 0 {
100+
stop += length
101+
}
102+
if start < 0 {
103+
start = 0
104+
} else if start >= length {
105+
start = length
106+
}
107+
if stop < 0 {
108+
stop = 0
109+
} else if stop >= length {
110+
stop = length
111+
}
112+
113+
startIndex := computeItem(r, Int(start))
114+
stopIndex := computeItem(r, Int(stop))
115+
stepIndex := Int(step) * r.Step
116+
117+
return &Range{
118+
Start: startIndex,
119+
Stop: stopIndex,
120+
Step: stepIndex,
121+
Length: Int(sliceLength),
122+
}, nil
123+
}
124+
82125
index, err := Index(key)
83126
if err != nil {
84127
return nil, err
85128
}
86-
// TODO(corona10): Support slice case
87-
length := computeRangeLength(r.Start, r.Stop, r.Step)
129+
88130
if index < 0 {
89131
index += length
90132
}

0 commit comments

Comments
 (0)