From 898df4bf3c2096fbcfe137086783f317608ae76f Mon Sep 17 00:00:00 2001 From: Nathan Villaescusa Date: Sat, 30 Mar 2024 02:45:40 -0700 Subject: [PATCH] Split out batch --- lib/iterator/batch.go | 32 +++++++++++++++++++ .../{iterator_test.go => batch_test.go} | 0 lib/iterator/iterator.go | 31 ------------------ 3 files changed, 32 insertions(+), 31 deletions(-) create mode 100644 lib/iterator/batch.go rename lib/iterator/{iterator_test.go => batch_test.go} (100%) diff --git a/lib/iterator/batch.go b/lib/iterator/batch.go new file mode 100644 index 00000000..f7b193ca --- /dev/null +++ b/lib/iterator/batch.go @@ -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 +} diff --git a/lib/iterator/iterator_test.go b/lib/iterator/batch_test.go similarity index 100% rename from lib/iterator/iterator_test.go rename to lib/iterator/batch_test.go diff --git a/lib/iterator/iterator.go b/lib/iterator/iterator.go index 58712fc5..9fbf9dd6 100644 --- a/lib/iterator/iterator.go +++ b/lib/iterator/iterator.go @@ -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 -}