mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-13 01:02:28 +08:00
list: add sublist method (#49)
SubList returns a sub list of the original list between the specified fromIndex, inclusive, and toIndex, exclusive.
This commit is contained in:
@@ -285,3 +285,11 @@ func (l *List[T]) Intersection(other *List[T]) *List[T] {
|
|||||||
|
|
||||||
return result
|
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)
|
||||||
|
}
|
||||||
|
|||||||
@@ -315,3 +315,19 @@ func TestIntersection(t *testing.T) {
|
|||||||
list3 := list1.Intersection(list2)
|
list3 := list1.Intersection(list2)
|
||||||
assert.Equal(true, expected.Equal(list3))
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ import (
|
|||||||
- [Unique](#Unique)
|
- [Unique](#Unique)
|
||||||
- [Union](#Union)
|
- [Union](#Union)
|
||||||
- [Intersection](#Intersection)
|
- [Intersection](#Intersection)
|
||||||
|
- [SubList](#SubList)
|
||||||
|
|
||||||
<div STYLE="page-break-after: always;"></div>
|
<div STYLE="page-break-after: always;"></div>
|
||||||
|
|
||||||
@@ -791,4 +792,32 @@ func main() {
|
|||||||
|
|
||||||
fmt.Println(li3.Data()) //4
|
fmt.Println(li3.Data()) //4
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### <span id="SubList">SubList</span>
|
||||||
|
<p>SubList returns a sub list of the original list between the specified fromIndex, inclusive, and toIndex, exclusive.</p>
|
||||||
|
|
||||||
|
<b>Signature:</b>
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (l *List[T]) SubList(fromIndex, toIndex int) *List[T]
|
||||||
|
```
|
||||||
|
<b>Example:</b>
|
||||||
|
|
||||||
|
```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}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
Reference in New Issue
Block a user