♻️ Refactor Incremental Generator to single function with options
This commit is contained in:
parent
63d538d889
commit
586fe4f1de
4 changed files with 176 additions and 182 deletions
55
gen_int.go
Normal file
55
gen_int.go
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
package nomino
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type incConf struct {
|
||||
start int
|
||||
step int
|
||||
cb func(int) string
|
||||
}
|
||||
|
||||
// IncrementalOption sets an option for the Incremental Generator
|
||||
type IncrementalOption func(c *incConf)
|
||||
|
||||
// Incremental generates a name that is a series of integers.
|
||||
// By default it begins at 0 and increments by 1 each time.
|
||||
func Incremental(opts ...IncrementalOption) Generator {
|
||||
c := incConf{step: 1, cb: strconv.Itoa}
|
||||
for _, opt := range opts {
|
||||
opt(&c)
|
||||
}
|
||||
|
||||
next := c.start
|
||||
return func(*Config) (string, error) {
|
||||
out := c.cb(next)
|
||||
next += c.step
|
||||
return out, nil
|
||||
}
|
||||
}
|
||||
|
||||
// IncrementalStart sets the starting integer for Incremental
|
||||
func IncrementalStart(start int) IncrementalOption {
|
||||
return func(c *incConf) {
|
||||
c.start = start
|
||||
}
|
||||
}
|
||||
|
||||
// IncrementalStepsets the step by which Incremental increases with each invocation.
|
||||
func IncrementalStep(step int) IncrementalOption {
|
||||
return func(c *incConf) {
|
||||
c.step = step
|
||||
}
|
||||
}
|
||||
|
||||
// IncrementalFormatsets the format for the number generated by Incremental.
|
||||
// It will be formatted with Printf. This is mostly likely useful with a format like "%02d"
|
||||
func IncrementalFormat(format string) IncrementalOption {
|
||||
return func(c *incConf) {
|
||||
c.cb = func(i int) string {
|
||||
return fmt.Sprintf(format, i)
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue