Passed
Pull Request — main (#40)
by Serhii
01:18
created

timeago.getRules   F

Complexity

Conditions 14

Size

Total Lines 23
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 19
dl 0
loc 23
rs 3.6
c 0
b 0
f 0
nop 2

How to fix   Complexity   

Complexity

Complex classes like timeago.getRules often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
package timeago
2
3
import (
4
	"strings"
5
)
6
7
type Rule struct {
8
	Zero  bool
9
	One   bool
10
	Two   bool
11
	Few   bool
12
	Many  bool
13
	Other bool
14
}
15
16
var grammarRules = func(num int) map[string]*Rule {
17
	end := num % 10
18
19
	return map[string]*Rule{
20
		"en,nl,de": {
21
			Zero: num == 0,
22
			One:  num == 1,
23
			Two:  num == 2,
24
			Few:  num > 1,
25
			Many: num > 1,
26
		},
27
		"ru,uk": {
28
			Zero: num == 0,
29
			One:  num == 1 || (num > 20 && end == 1),
30
			Two:  num == 2,
31
			Few:  end == 2 || end == 3 || end == 4,
32
			Many: (num >= 5 && num <= 20) || end == 0 || (end >= 5 && end <= 9),
33
		},
34
	}
35
}
36
37
func identifyGrammarRules(num int, lang string) (*Rule, error) {
38
	rules := grammarRules(num)
39
40
	if v, ok := rules[lang]; ok {
41
		return v, nil
42
	}
43
44
	for langs, v := range rules {
45
		if strings.Contains(langs, lang) {
46
			return v, nil
47
		}
48
	}
49
50
	return nil, errorf("Language '" + lang + "' not found")
51
}
52