1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add IndexOf and LastIndexOf for stream

This commit is contained in:
dudaodong
2024-11-11 10:52:29 +08:00
parent de877e5278
commit f3579fc142
7 changed files with 263 additions and 62 deletions

View File

@@ -393,6 +393,26 @@ func (s Stream[T]) Min(less func(a, b T) bool) (T, bool) {
return min, true
}
// IndexOf returns the index of the first occurrence of the specified element in this stream, or -1 if this stream does not contain the element.
func (s Stream[T]) IndexOf(target T, equal func(a, b T) bool) int {
for i, v := range s.source {
if equal(v, target) {
return i
}
}
return -1
}
// LastIndexOf returns the index of the last occurrence of the specified element in this stream, or -1 if this stream does not contain the element.
func (s Stream[T]) LastIndexOf(target T, equal func(a, b T) bool) int {
for i := len(s.source) - 1; i >= 0; i-- {
if equal(s.source[i], target) {
return i
}
}
return -1
}
// ToSlice return the elements in the stream.
// Play: https://go.dev/play/p/jI6_iZZuVFE
func (s Stream[T]) ToSlice() []T {

View File

@@ -384,3 +384,31 @@ func ExampleStream_Count() {
// 3
// 0
}
func ExampleStream_IndexOf() {
s := FromSlice([]int{1, 2, 3, 2})
result1 := s.IndexOf(0, func(a, b int) bool { return a == b })
result2 := s.IndexOf(2, func(a, b int) bool { return a == b })
fmt.Println(result1)
fmt.Println(result2)
// Output:
// -1
// 1
}
func ExampleStream_LastIndexOf() {
s := FromSlice([]int{1, 2, 3, 2})
result1 := s.LastIndexOf(0, func(a, b int) bool { return a == b })
result2 := s.LastIndexOf(2, func(a, b int) bool { return a == b })
fmt.Println(result1)
fmt.Println(result2)
// Output:
// -1
// 3
}

View File

@@ -381,3 +381,22 @@ func TestStream_Min(t *testing.T) {
assert.Equal(1, max)
assert.Equal(true, ok)
}
func TestStream_IndexOf(t *testing.T) {
assert := internal.NewAssert(t, "TestStream_IndexOf")
s := FromSlice([]int{4, 2, 1, 3, 4})
assert.Equal(-1, s.IndexOf(0, func(a, b int) bool { return a == b }))
assert.Equal(0, s.IndexOf(4, func(a, b int) bool { return a == b }))
assert.Equal(3, s.IndexOf(3, func(a, b int) bool { return a == b }))
}
func TestStream_LastIndexOf(t *testing.T) {
assert := internal.NewAssert(t, "TestStream_LastIndexOf")
s := FromSlice([]int{4, 2, 1, 3, 2})
assert.Equal(-1, s.LastIndexOf(0, func(a, b int) bool { return a == b }))
assert.Equal(4, s.LastIndexOf(2, func(a, b int) bool { return a == b }))
}