/
pairwise.go
56 lines (50 loc) · 1.36 KB
/
pairwise.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
package arangodb
import (
"errors"
"github.com/dictyBase/modware-stock/internal/model"
)
// PairWiseIterator is the container for iterator
type PairWiseIterator struct {
slice []*model.StockDoc
// keeps track of the first index
firstIdx int
// keeps track of the next index in the pair
secondIdx int
// last index of the slice
lastIdx int
// toogle the state for fetching the first pair
firstPair bool
}
// NewPairWiseIterator is the constructor, returns error in case of empty or
// slice with single element
func NewPairWiseIterator(m []*model.StockDoc) (*PairWiseIterator, error) {
if len(m) <= 1 {
return &PairWiseIterator{}, errors.New("not enough element to fetch pairs")
}
return &PairWiseIterator{
slice: m,
firstIdx: 0,
secondIdx: 1,
lastIdx: len(m) - 1,
firstPair: true,
}, nil
}
// NextPair moves the iteration to the next pair. If NextPair() returns true
// the pair could be retrieved by Pair() method. If it is called for the first
// time it points to the first pair.
func (p *PairWiseIterator) NextPair() bool {
if p.firstPair {
p.firstPair = false
return true
}
if p.secondIdx == p.lastIdx {
return false
}
p.firstIdx++
p.secondIdx++
return true
}
// Pair retrieves the pair of elements from the slice
func (p *PairWiseIterator) Pair() (*model.StockDoc, *model.StockDoc) {
return p.slice[p.firstIdx], p.slice[p.secondIdx]
}