From 8883abd461baf1a7c49560ea08c3e798df315b41 Mon Sep 17 00:00:00 2001 From: bandl <1658002533@qq.com> Date: Fri, 22 Oct 2021 22:01:48 +0800 Subject: [PATCH] feat(listx): add range func --- pkg/structure/listx/listx.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/pkg/structure/listx/listx.go b/pkg/structure/listx/listx.go index 9c45d18..c804c91 100644 --- a/pkg/structure/listx/listx.go +++ b/pkg/structure/listx/listx.go @@ -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 +}