-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
24ed846
commit 898df4b
Showing
3 changed files
with
32 additions
and
31 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
package iterator | ||
|
||
import "fmt" | ||
|
||
type batchIterator[T any] struct { | ||
items []T | ||
index int | ||
step int | ||
} | ||
|
||
// Returns an iterater that splits a list of items into batches of the given step size. | ||
func NewBatchIterator[T any](items []T, step int) Iterator[[]T] { | ||
return &batchIterator[T]{ | ||
items: items, | ||
index: 0, | ||
step: max(step, 1), | ||
} | ||
} | ||
|
||
func (i *batchIterator[T]) HasNext() bool { | ||
return i.index < len(i.items) | ||
} | ||
|
||
func (i *batchIterator[T]) Next() ([]T, error) { | ||
if !i.HasNext() { | ||
return nil, fmt.Errorf("iterator has finished") | ||
} | ||
end := min(i.index+i.step, len(i.items)) | ||
result := i.items[i.index:end] | ||
i.index = end | ||
return result, nil | ||
} |
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,37 +1,6 @@ | ||
package iterator | ||
|
||
import "fmt" | ||
|
||
type Iterator[T any] interface { | ||
HasNext() bool | ||
Next() (T, error) | ||
} | ||
|
||
type batchIterator[T any] struct { | ||
items []T | ||
index int | ||
step int | ||
} | ||
|
||
// Returns an iterater that splits a list of items into batches of the given step size. | ||
func NewBatchIterator[T any](items []T, step int) Iterator[[]T] { | ||
return &batchIterator[T]{ | ||
items: items, | ||
index: 0, | ||
step: max(step, 1), | ||
} | ||
} | ||
|
||
func (i *batchIterator[T]) HasNext() bool { | ||
return i.index < len(i.items) | ||
} | ||
|
||
func (i *batchIterator[T]) Next() ([]T, error) { | ||
if !i.HasNext() { | ||
return nil, fmt.Errorf("iterator has finished") | ||
} | ||
end := min(i.index+i.step, len(i.items)) | ||
result := i.items[i.index:end] | ||
i.index = end | ||
return result, nil | ||
} |