Added Iterator interface and two implementation: list itrator and range iterator
This commit is contained in:
parent
e012afa691
commit
836a9165a5
55
it-range.go
Normal file
55
it-range.go
Normal file
@ -0,0 +1,55 @@
|
||||
// it-range.go
|
||||
package expr
|
||||
|
||||
import "io"
|
||||
|
||||
type RangeIterator struct {
|
||||
start int64
|
||||
end int64
|
||||
step int64
|
||||
current int64
|
||||
index int
|
||||
}
|
||||
|
||||
func NewRangeIterator(start, end, step int64) *RangeIterator {
|
||||
if step == 0 {
|
||||
panic("Range step must be not zero")
|
||||
}
|
||||
if step < 0 && start < end {
|
||||
panic("When the range's step is less than zero, start must be greater than end")
|
||||
}
|
||||
if step > 0 && start > end {
|
||||
panic("When the range's step is greater than zero, start must be less than end")
|
||||
}
|
||||
return &RangeIterator{start: start, end: end, step: step, current: start, index: 0}
|
||||
}
|
||||
|
||||
func (it *RangeIterator) Reset() {
|
||||
it.index = 0
|
||||
it.current = it.start
|
||||
}
|
||||
|
||||
func (it *RangeIterator) Next() (item any, err error) {
|
||||
if it.step > 0 {
|
||||
if it.current < it.end {
|
||||
item = it.current
|
||||
it.current += it.step
|
||||
it.index++
|
||||
} else {
|
||||
err = io.EOF
|
||||
}
|
||||
} else {
|
||||
if it.current > it.end {
|
||||
item = it.current
|
||||
it.current += it.step
|
||||
it.index++
|
||||
} else {
|
||||
err = io.EOF
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (it *RangeIterator) Index() int {
|
||||
return it.index - 1
|
||||
}
|
37
iterator.go
Normal file
37
iterator.go
Normal file
@ -0,0 +1,37 @@
|
||||
// iterator.go
|
||||
package expr
|
||||
|
||||
import "io"
|
||||
|
||||
type Iterator interface {
|
||||
Reset()
|
||||
Next() (item any, err error) // must return io.EOF after the last item
|
||||
Index() int
|
||||
}
|
||||
|
||||
type FlatArrayIterator struct {
|
||||
a []any
|
||||
index int
|
||||
}
|
||||
|
||||
func NewFlatArrayIterator(array []any) *FlatArrayIterator {
|
||||
return &FlatArrayIterator{a: array, index: 0}
|
||||
}
|
||||
|
||||
func (it *FlatArrayIterator) Reset() {
|
||||
it.index = 0
|
||||
}
|
||||
|
||||
func (it *FlatArrayIterator) Next() (item any, err error) {
|
||||
if it.index < len(it.a) {
|
||||
item = it.a[it.index]
|
||||
it.index++
|
||||
} else {
|
||||
err = io.EOF
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (it *FlatArrayIterator) Index() int {
|
||||
return it.index - 1
|
||||
}
|
Loading…
Reference in New Issue
Block a user