File size: 1,187 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package main

import (
	"strings"
	"sync"

	"github.com/brianvoe/gofakeit/v6"
)

// uniqGen allows generating unique string values.
type uniqGen struct {
	f  *gofakeit.Faker
	m  map[strScope]int
	mx sync.Mutex
}

type strScope struct {
	scope string
	value string
}

func newGen(f *gofakeit.Faker) *uniqGen {
	return &uniqGen{
		f: f,
		m: make(map[strScope]int, 100000),
	}
}

// PickOne will return a random item from a slice, and will not return the
// same value twice.
func (g *uniqGen) PickOne(s []string) string {
	return g.Gen(func() string { return g.f.RandomString(s) })
}

// Gen will call `fn` until a unique value is returned.
func (g *uniqGen) Gen(fn func() string, scope ...string) string { return g.GenN(1, fn, scope...) }

// Gen will call `fn` until a value that has been returned less than N is provided.
func (g *uniqGen) GenN(n int, fn func() string, scope ...string) string {
	g.mx.Lock()
	defer g.mx.Unlock()
	scopeVal := strings.Join(scope, "|")
	var i int
	for {
		if i > 5 {
			panic("aborted after 5 tries")
		}
		scope := strScope{
			scope: scopeVal,
			value: fn(),
		}
		if g.m[scope] >= n {
			i++
			continue
		}
		g.m[scope]++
		return scope.value
	}
}