Passed
Pull Request — master (#4)
by felipe
01:40
created

rollout.*Rollout.Set   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 1
dl 0
loc 2
ccs 1
cts 1
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
package rollout
2
3
import "hash/crc32"
4
import "math"
5
6
// Feature struct keeps the main information of a feature as:
7
// identification, the percentage of users that will be affected and status
8
type Feature struct {
9
	Name       string
10
	Percentage float64
11
	Active     bool
12
}
13
14
// Rollout component struct
15
type Rollout struct {
16
	features map[string]Feature
17
}
18
19
// IsActive will check if a given user is active for a feature
20
func (r Rollout) IsActive(feature string, id string) bool {
21 1
	f, ok := r.features[feature]
22 1
	crc32q := crc32.MakeTable(0xEDB88320)
23 1
	crc32 := crc32.Checksum([]byte(id), crc32q)
24 1
	return ok && f.Percentage > math.Mod(float64(crc32), 100)
25
}
26
27
// IsFeatureActive checks if a feature is active
28
func (r Rollout) IsFeatureActive(feature string) bool {
29 1
	f, ok := r.features[feature]
30 1
	return ok && f.Active
31
}
32
33
// Activate active a feature
34
// if the feature does not exists the action is ignored
35
func (r *Rollout) Activate(feature string) {
36 1
	f, ok := r.features[feature]
37 1
	if ok {
38 1
		f.Active = true
39 1
		r.Set(f)
40
	}
41
}
42
43
// Deactivate deactivate a feature
44
// if the feature does not exists the action is ignored
45
func (r *Rollout) Deactivate(feature string) {
46 1
	f, ok := r.features[feature]
47 1
	if ok {
48 1
		f.Active = false
49 1
		r.Set(f)
50
	}
51
}
52
53
// Set upsert a feature inside rollout component
54
func (r *Rollout) Set(feature Feature) {
55 1
	r.features[feature.Name] = feature
56
}
57
58
// Create is function used to create a new Rollout
59
func Create(features []Feature) *Rollout {
60 1
	r := Rollout{}
61 1
	r.features = make(map[string]Feature)
62 1
	for _, v := range features {
63 1
		r.features[v.Name] = v
64
	}
65 1
	return &r
66
}
67
68
// Get a feature by name
69
func (r Rollout) Get(feature string) (Feature, bool) {
70 1
	f, ok := r.features[feature]
71 1
	return f, ok
72
}
73
74
// GetAll get all features
75
func (r Rollout) GetAll() []Feature {
76 1
	var features []Feature
77 1
	for _, el := range r.features {
78 1
		features = append(features, el)
79
	}
80 1
	return features
81
}
82