File size: 856 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
package main

import (
	"strings"
	"sync"

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

// uniqIntGen works like uniqGen but returns integers.
type uniqIntGen struct {
	f  *gofakeit.Faker
	m  map[intScope]bool
	mx sync.Mutex
}

type intScope struct {
	scope string
	value int
}

func newUniqIntGen(f *gofakeit.Faker) *uniqIntGen {
	return &uniqIntGen{
		f: f,
		m: make(map[intScope]bool),
	}
}

// Gen will return a random value from 0 to n (non-inclusive).
//
// It will always return a unique value.
func (g *uniqIntGen) Gen(n int, scope ...string) int {
	g.mx.Lock()
	defer g.mx.Unlock()
	scopeVal := strings.Join(scope, "|")
	var i int
	for {
		if i > 5 {
			panic("aborted after 5 tries")
		}
		scope := intScope{
			value: g.f.IntRange(0, n-1),
			scope: scopeVal,
		}
		if g.m[scope] {
			i++
			continue
		}
		g.m[scope] = true
		return scope.value
	}
}