Skip to content

Commit

Permalink
Split out batch
Browse files Browse the repository at this point in the history
  • Loading branch information
nathan-artie committed Mar 30, 2024
1 parent 24ed846 commit 898df4b
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 31 deletions.
32 changes: 32 additions & 0 deletions lib/iterator/batch.go
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.
31 changes: 0 additions & 31 deletions lib/iterator/iterator.go
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
}

0 comments on commit 898df4b

Please sign in to comment.