-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterator.go
85 lines (70 loc) · 1.38 KB
/
iterator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package iterator
import (
"fmt"
)
/*
Part 1: Here's the interface for an iterator. Implement it.
class Iterator {
// candidate should insert constructor here
boolean hasNext();
Object next();
}
it = Iterator([1, 2, 3])
while it.hasNext():
print it.next()
# 1
# 2
# 3
*/
type Iterator struct {
data []interface{}
currentIdx uint64
}
func (i *Iterator) reset() {
i.currentIdx = 0
}
func (i *Iterator) Next() interface{} {
value := i.data[i.currentIdx]
i.currentIdx++
return value
}
func (i *Iterator) HasNext() bool {
if i.currentIdx < uint64(len(i.data)) {
return true
}
defer i.reset()
return false
}
func NewIterator() *Iterator {
i := Iterator{}
return &i
}
func (i *Iterator) Init(arr []interface{}) {
i.data = arr
i.currentIdx = uint64(0)
}
type FlatteningIterator struct {
it *Iterator
currentIdx uint64
}
func NewFlatteningIterator(it *Iterator) *FlatteningIterator {
fl := FlatteningIterator{
it: it,
currentIdx: uint64(0),
}
return &fl
}
func (f *FlatteningIterator) HasNext() bool {
return f.it.HasNext()
}
func (f *FlatteningIterator) Next() {
// next is func (i *Iterator) Next() interface{} {
// so now its a function and we need to print the values in this function
// we can do this by calling this function...
next := f.it.Next()
it := next.(*Iterator)
for it.HasNext() {
fmt.Println(it.Next())
}
return
}