-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringrandomizer.go
More file actions
88 lines (76 loc) · 2.39 KB
/
Copy pathstringrandomizer.go
File metadata and controls
88 lines (76 loc) · 2.39 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Package go_string_randomizer Package provides small and optimized functions to generate
//random strings that can be used as passwords, control ids, etc.
package go_string_randomizer
import (
"fmt"
"math"
"math/rand"
)
type StringRandomizer struct {
LettersUniverse string
GeneratedMaxLen int
NoCollisions bool
RandSeed int
}
// GenerateOne - generates 1 randomized string based on the struct initialization vars
func (s StringRandomizer) GenerateOne() string {
rand.Seed(int64(s.RandSeed))
id := make([]rune, s.GeneratedMaxLen)
letters := []rune(s.LettersUniverse)
for i := 0; i < s.GeneratedMaxLen; i++ {
id[i] = letters[rand.Intn(len(letters))]
}
return string(id)
}
// GenerateBulk - generates amount arg of randomized string based on the struct initialization vars
func (s StringRandomizer) GenerateBulk(amount int) (error, []string) {
var err error
var result []string
if s.NoCollisions {
err = s.validatePermutationsAmount(amount)
}
if err != nil {
return err, result
}
rand.Seed(int64(s.RandSeed))
collisionControl := make(map[string]bool)
letters := []rune(s.LettersUniverse)
for len(result) != amount {
id := make([]rune, s.GeneratedMaxLen)
for i := 0; i < s.GeneratedMaxLen; i++ {
id[i] = letters[rand.Intn(len(letters))]
}
if s.NoCollisions {
if !s.isCollision(collisionControl, string(id)) {
result = append(result, string(id))
}
} else {
result = append(result, string(id))
}
}
return err, result
}
// GetUniquePermutationsAmt Gets the max number of possible permutations given the struct initialization args
func (s StringRandomizer) GetUniquePermutationsAmt() float64 {
return math.Pow(
float64(len(s.LettersUniverse)),
float64(s.GeneratedMaxLen),
)
}
//helper function that checks collisions when attrib NoCollisions on the struct is set to true
func (s StringRandomizer) isCollision(controlMap map[string]bool, item string) bool {
if _, exists := controlMap[item]; !exists {
controlMap[item] = true
return false
}
return true
}
//helper function that validates the max unique permutations amount
func (s StringRandomizer) validatePermutationsAmount(amountToGenerate int) error {
var err error
if float64(amountToGenerate) > s.GetUniquePermutationsAmt() {
err = fmt.Errorf("the amount desired for generation (%v) is higher than the possible combinations (%v)",
amountToGenerate, s.GetUniquePermutationsAmt())
}
return err
}