-
Notifications
You must be signed in to change notification settings - Fork 0
/
codabar.go
52 lines (41 loc) · 1.12 KB
/
codabar.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
package codabar
import (
"errors"
"fmt"
)
type codabar string
var ErrInvalidArgument = errors.New("invalid argument")
type Option func(*codabarConfig)
type codabarConfig struct {
checkDigitStrategy CheckDigitStrategy
seedGenerator func(body) (seed, error)
}
func WithCheckDigit(strategy CheckDigitStrategy) Option {
return func(cfg *codabarConfig) {
cfg.checkDigitStrategy = strategy
}
}
func WithSeed(generator func(body) (seed, error)) Option {
return func(cfg *codabarConfig) {
cfg.seedGenerator = generator
}
}
func NewCodabar(prefix prefix, b body, suffix suffix, opts ...Option) (codabar, error) {
cfg := &codabarConfig{
seedGenerator: func(b body) (seed, error) {
return NewSeed(string(b))
},
}
for _, opt := range opts {
opt(cfg)
}
if cfg.checkDigitStrategy != nil {
seed, err := cfg.seedGenerator(b)
if err != nil {
return codabar(""), fmt.Errorf(": %w %s", ErrInvalidArgument, b)
}
checkDigit := cfg.checkDigitStrategy(seed)
return codabar(string(prefix) + string(b) + string(checkDigit) + string(suffix)), nil
}
return codabar(string(prefix) + string(b) + string(suffix)), nil
}