diff --git a/datastructure/list/list.go b/datastructure/list/list.go index 769fcbe..2c87e33 100644 --- a/datastructure/list/list.go +++ b/datastructure/list/list.go @@ -285,3 +285,11 @@ func (l *List[T]) Intersection(other *List[T]) *List[T] { return result } + +// SubList returns a sub list of the original list between the specified fromIndex, inclusive, and toIndex, exclusive. +func (l *List[T]) SubList(fromIndex, toIndex int) *List[T] { + data := l.data[fromIndex:toIndex] + subList := make([]T, len(data)) + copy(subList, data) + return NewList(subList) +} diff --git a/datastructure/list/list_test.go b/datastructure/list/list_test.go index e62bffd..d3636c3 100644 --- a/datastructure/list/list_test.go +++ b/datastructure/list/list_test.go @@ -315,3 +315,19 @@ func TestIntersection(t *testing.T) { list3 := list1.Intersection(list2) assert.Equal(true, expected.Equal(list3)) } + +func TestSubSlice(t *testing.T) { + assert := internal.NewAssert(t, "TestSubSlice") + + list := NewList([]int{1, 2, 3, 4, 5, 8}) + subList := list.SubList(2, 5) + + assert.Equal([]int{3, 4, 5}, subList.Data()) +} + +func BenchmarkSubSlice(b *testing.B) { + list := NewList([]int{1, 2, 3, 4, 5, 8}) + for n := 0; n < b.N; n++ { + list.SubList(2, 5) + } +} diff --git a/docs/datastructure/list.md b/docs/datastructure/list.md index 097c28b..fd130d5 100644 --- a/docs/datastructure/list.md +++ b/docs/datastructure/list.md @@ -46,6 +46,7 @@ import ( - [Unique](#Unique) - [Union](#Union) - [Intersection](#Intersection) +- [SubList](#SubList)
@@ -791,4 +792,32 @@ func main() { fmt.Println(li3.Data()) //4 } +``` + + + + +### SubList +SubList returns a sub list of the original list between the specified fromIndex, inclusive, and toIndex, exclusive.
+ +Signature: + +```go +func (l *List[T]) SubList(fromIndex, toIndex int) *List[T] +``` +Example: + +```go +package main + +import ( + "fmt" + list "github.com/duke-git/lancet/v2/datastructure/list" +) + +func main() { + l := list.NewList([]int{1, 2, 3, 4, 5, 6}) + + fmt.Println(l.SubList(2, 5)) // []int{3, 4, 5} +} ``` \ No newline at end of file