-
Notifications
You must be signed in to change notification settings - Fork 7
/
random-numeric-string.go
70 lines (54 loc) · 1.42 KB
/
random-numeric-string.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
68
69
70
package handy
import (
"strconv"
"strings"
)
// RandomNumericString returns a string with length between given lengthMin and lengthMax
// Any digit within forbiddenDigits param will be ignored
// Example: https://play.golang.org/p/phF-y9ZsUIP
func RandomNumericString(forbiddenDigits []int, lengthMin, lengthMax int) string {
length := 0
switch {
case lengthMax < lengthMin:
//panic(fmt.Sprintf("handy.RandomNumericString() lengthMax %d is smaller than lengthMix %d", lengthMax, lengthMin))
// Instead of panic, return empty
return ""
case lengthMax == lengthMin:
length = lengthMax
default:
length = RandomInt(lengthMin, lengthMax)
}
if length == 0 {
return ""
}
allowedDigits := map[int]bool{0: true, 1: true, 2: true, 3: true, 4: true, 5: true, 6: true, 7: true, 8: true, 9: true}
if len(forbiddenDigits) > 0 {
for _, k := range forbiddenDigits {
allowedDigits[k] = false
}
// Check if any digit remains allowed
var remainingAllowed []int
for k, b := range allowedDigits {
if b {
remainingAllowed = append(remainingAllowed, k)
}
}
if len(remainingAllowed) == 0 {
return ""
}
if len(remainingAllowed) == 1 {
return strings.Repeat(strconv.Itoa(remainingAllowed[0]), length)
}
}
s := make([]string, length)
for i := 0; i < length; i++ {
for {
x := RandomInt(0, 9)
if allowedDigits[x] {
s[i] = strconv.Itoa(x)
break
}
}
}
return strings.Join(s, "")
}