Skip to content

Commit

Permalink
fix docs for randomInt and update code to support documented third ar…
Browse files Browse the repository at this point in the history
…gument

Fixes: bxcodec#142
  • Loading branch information
maco committed Oct 21, 2021
1 parent 7460bf3 commit 251ff2e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 9 deletions.
28 changes: 19 additions & 9 deletions faker.go
Original file line number Diff line number Diff line change
Expand Up @@ -1157,24 +1157,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
Original file line number Diff line number Diff line change
Expand Up @@ -841,6 +841,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

0 comments on commit 251ff2e

Please sign in to comment.