feat(listx): add range func

This commit is contained in:
bandl 2021-10-22 22:01:48 +08:00
parent 8c5c594ac5
commit 8883abd461
1 changed files with 28 additions and 0 deletions

View File

@ -333,3 +333,31 @@ func (l *Listx) Slice(start int, end int) (structure.UpdateLength, error) {
return structure.UpdateLength(updateLength), nil
}
func (l *Listx) Range(start, end int) ([]string, error) {
startOffset, err := l.rightIndex(start)
if err != nil {
return nil, err
}
endRightOffset, err := l.rightIndex(end)
if err != nil && end != l.length {
return nil, errorx.New("index overstep the boundary, index: %d", end)
}
if startOffset >= endRightOffset && endRightOffset != 0 {
return nil, errorx.New("the start index must be larger than the end index")
}
head := l.head
for nodePoint := 0; head != nil && nodePoint < startOffset; nodePoint++ {
head = head.next
}
values := make([]string, 0)
for i := 0; i < endRightOffset-startOffset && head != nil; i++ {
values = append(values, head.val.ToString())
head = head.next
}
return values, nil
}