-
Notifications
You must be signed in to change notification settings - Fork 246
/
Copy pathiterator.go
91 lines (77 loc) · 1.62 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
86
87
88
89
90
91
// Package iterator is an example of the Iterator Pattern.
package iterator
// Iterator provides a iterator interface.
type Iterator interface {
Index() int
Value() interface{}
Has() bool
Next()
Prev()
Reset()
End()
}
// Aggregate provides a collection interface.
type Aggregate interface {
Iterator() Iterator
}
// BookIterator implements the Iterator interface.
type BookIterator struct {
shelf *BookShelf
index int
internal int
}
// Index returns current index
func (i *BookIterator) Index() int {
return i.index
}
// Value returns current value
func (i *BookIterator) Value() interface{} {
return i.shelf.Books[i.index]
}
// Has implementation.
func (i *BookIterator) Has() bool {
if i.internal < 0 || i.internal >= len(i.shelf.Books) {
return false
}
return true
}
// Next goes to the next item.
func (i *BookIterator) Next() {
i.internal++
if i.Has() {
i.index++
}
}
// Prev goes to the previous item.
func (i *BookIterator) Prev() {
i.internal--
if i.Has() {
i.index--
}
}
// Reset resets iterator.
func (i *BookIterator) Reset() {
i.index = 0
i.internal = 0
}
// End goes to the last item.
func (i *BookIterator) End() {
i.index = len(i.shelf.Books) - 1
i.internal = i.index
}
// BookShelf implements the Aggregate interface.
type BookShelf struct {
Books []*Book
}
// Iterator creates and returns the iterator over the collection.
func (b *BookShelf) Iterator() Iterator {
return &BookIterator{shelf: b}
}
// Add adds an item to the collection.
func (b *BookShelf) Add(book *Book) {
b.Books = append(b.Books, book)
}
// Book implements a item of the collection.
type Book struct {
Name string
}