str2pad := "12"
padWith := "0"
amt2pad := 6
//This will make sure there is always 6 characters total, padded on the right side
//Note to check if strings.Repeat returns a negative value
paddedStr := str2pad + strings.Repeat(padWith, amt2pad - len(str2pad))
//Outputs 120000
// Random is basically just a rand.Rand in this case
func (r Random) codeWithFmt(length int) string {
max := int64(math.Pow10(length)) - 1
var v int64
for v == 0 {
v = r.Int63n(max)
}
return fmt.Sprintf("%0*d", length, v)
}
func (r Random) Code(digits int) string {
max := int64(math.Pow10(digits)) - 1
var v int64
for v == 0 {
v = r.Int63n(max)
}
var padding int
if math.Pow10(digits-1)-float64(v) > 0 {
lv := math.Log10(float64(v))
if lv == float64(int64(lv)) {
lv++
}
padding = digits - int(math.Ceil(lv))
}
builder := strings.Builder{}
builder.Grow(digits * 4)
for i := 0; i < padding; i++ {
builder.WriteRune('0')
}
builder.WriteString(strconv.FormatInt(v, 10))
return builder.String()
}
func BenchmarkCodeGeneration(b *testing.B) {
assert := require.New(b)
_ = assert
r := New()
for i := 0; i < b.N; i++ {
// assert.Len(r.Code(7), 7)
r.Code(7)
}
}
func BenchmarkCodeGenerationWithFmt(b *testing.B) {
assert := require.New(b)
_ = assert
r := New()
for i := 0; i < b.N; i++ {
// assert.Len(r.codeWithFmt(7), 7)
r.codeWithFmt(7)
}
}