diff --git a/faker_test.go b/faker_test.go index c42cf2d..5f7324e 100644 --- a/faker_test.go +++ b/faker_test.go @@ -556,6 +556,13 @@ func TestMap(t *testing.T) { Expect(t, true, len(mp) > 0) } +func TestRandomStringElement(t *testing.T) { + f := New() + m := []string{"str1", "str2"} + randomStr := f.RandomStringElement(m) + Expect(t, true, randomStr == "str1" || randomStr == "str2") +} + func TestRandomStringMapKey(t *testing.T) { f := New() m := map[string]string{"k0": "v0", "k1": "v1"} diff --git a/random_element.go b/random_element.go new file mode 100644 index 0000000..0b33ebd --- /dev/null +++ b/random_element.go @@ -0,0 +1,26 @@ +package faker + +// RandomElement returns a fake random element from a given list of elements +func RandomElement[T any](f Faker, elements ...T) T { + i := f.IntBetween(0, len(elements)-1) + return elements[i] +} + +// RandomElementWeighted takes faker instance and a list of elements in the form of map[weight]element, +// it then selects one of the elements randomly and returns it, +// +// Elements with higher weight have more chance to be returned. +func RandomElementWeighted[T any](f Faker, elements map[int]T) T { + arrayOfElements := make([]T, 0) + + for weight, value := range elements { + // TODO: there is an accepted proposal for generic slices.Repeat function in Go 1.23 + for i := 0; i < weight; i++ { + arrayOfElements = append(arrayOfElements, value) + } + } + + i := f.IntBetween(0, len(arrayOfElements)-1) + + return arrayOfElements[i] +} diff --git a/random_element_test.go b/random_element_test.go new file mode 100644 index 0000000..c969fba --- /dev/null +++ b/random_element_test.go @@ -0,0 +1,25 @@ +package faker + +import "testing" + +func TestRandomElement(t *testing.T) { + f := New() + m := []string{"str1", "str2"} + randomStr := RandomElement(f, m...) + Expect(t, true, randomStr == "str1" || randomStr == "str2") +} + +func TestRandomElementWeighted(t *testing.T) { + f := New() + m := map[int]string{ + 0: "zeroChance", + 1: "someChance", + 5: "moreChance", + } + + for i := 0; i < 5; i++ { + got := RandomElementWeighted(f, m) + Expect(t, true, got == "someChance" || got == "moreChance") + Expect(t, true, got != "zeroChance") + } +} diff --git a/time.go b/time.go index 0416461..89d8735 100644 --- a/time.go +++ b/time.go @@ -33,7 +33,7 @@ func (t Time) TimeBetween(min, max time.Time) time.Time { // ISO8601 returns a fake time in ISO8601 format for Time func (t Time) ISO8601(max time.Time) string { t1 := t.Time(max) - return t1.Format("2006-02-01T15:04:05+000") + return t1.Format("2006-01-02T15:04:05+000") } // ANSIC returns a fake time in ANSIC format for Time