Skip to content
This repository has been archived by the owner on Dec 8, 2022. It is now read-only.

feat: randomInt support third argument #150

Merged
merged 3 commits into from Dec 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 19 additions & 9 deletions faker.go
Expand Up @@ -1161,24 +1161,34 @@ func randomStringNumber(n int) string {
}

// RandomInt Get three parameters , only first mandatory and the rest are optional
// If only set one parameter : This means the minimum number of digits and the total number
// If only set two parameters : First this is min digit and second max digit and the total number the difference between them
// If only three parameters: the third argument set Max count Digit
// (minimum_int, maximum_int, count)
// If only set one parameter : An integer greater than minimum_int will be returned
// If only set two parameters : All integers between minimum_int and maximum_int will be returned, in a random order.
// If three parameters: `count` integers between minimum_int and maximum_int will be returned.
func RandomInt(parameters ...int) (p []int, err error) {
switch len(parameters) {
case 1:
minCount := parameters[0]
p = rand.Perm(minCount)
minInt := parameters[0]
p = rand.Perm(minInt)
for i := range p {
p[i] += minCount
p[i] += minInt
}
case 2:
minDigit, maxDigit := parameters[0], parameters[1]
p = rand.Perm(maxDigit - minDigit + 1)
minInt, maxInt := parameters[0], parameters[1]
p = rand.Perm(maxInt - minInt + 1)

for i := range p {
p[i] += minDigit
p[i] += minInt
}
case 3:
minInt, maxInt := parameters[0], parameters[1]
count := parameters[2]
p = rand.Perm(maxInt - minInt + 1)

for i := range p {
p[i] += minInt
}
p = p[0:count]
default:
err = fmt.Errorf(ErrMoreArguments, len(parameters))
}
Expand Down
19 changes: 19 additions & 0 deletions faker_test.go
Expand Up @@ -857,6 +857,25 @@ func TestRandomIntOnlySecondParameters(t *testing.T) {
}
}

func TestRandomIntThreeParameters(t *testing.T) {
first := rand.Intn(50)
second := rand.Intn(100) + first
third := rand.Intn(5)
res, _ := RandomInt(first, second, third)
if len(res) != (third) {
t.Errorf("Incorrect number of results returned. Expected %v. Got %v.", third, len(res))
}

for _, v := range res {
if v < first {
t.Errorf("Found value %v below minimum %v.", v, first)
}
if v > second {
t.Errorf("Found value %v above maximum %v.", v, second)
}
}
}

func TestRandomIntOnlyError(t *testing.T) {
arguments := []int{1, 3, 4, 5, 6}
_, err := RandomInt(arguments...)
Expand Down