-
Notifications
You must be signed in to change notification settings - Fork 0
/
segmenter.go
67 lines (60 loc) · 1.55 KB
/
segmenter.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
package segmenter
import (
"fmt"
"math"
"gopkg.in/validator.v2"
)
// Segmenter is used for loading strings in segment
type Segmenter[T comparable] struct {
slice []T
startIdx int
endIdx int
segmentLength int
numOps int
opsCounter int
}
// Config holds configuration for Segmenter
type Config[T comparable] struct {
Slice []T `validate:"min=1"`
SegmentLength int `validate:"min=1"`
}
// New returns new instance of Segmenter
func New[T comparable](cfg Config[T]) (*Segmenter[T], error) {
// validate config
err := validator.Validate(cfg)
if err != nil {
return nil, fmt.Errorf("invalid config: %w", err)
}
// construct segmenter
segmenter := &Segmenter[T]{
slice: cfg.Slice,
segmentLength: cfg.SegmentLength,
startIdx: 0,
endIdx: cfg.SegmentLength,
numOps: int(math.Ceil(float64(len(cfg.Slice)) / float64(cfg.SegmentLength))),
opsCounter: 0,
}
if segmenter.endIdx > len(cfg.Slice) {
segmenter.endIdx = len(cfg.Slice)
}
return segmenter, nil
}
// Next returns next segment. In case there is no longer next segment, it returns nil
func (s *Segmenter[T]) Next() []T {
if s.opsCounter == s.numOps {
return nil
}
defer func() {
s.opsCounter++
s.startIdx = s.opsCounter * s.segmentLength
s.endIdx = s.startIdx + s.segmentLength
if s.endIdx > len(s.slice) {
s.endIdx = len(s.slice)
}
}()
return s.slice[s.startIdx:s.endIdx]
}
// HasNext returns true when Segmenter still has next segment
func (s *Segmenter[_]) HasNext() bool {
return s.opsCounter < s.numOps
}