-
Notifications
You must be signed in to change notification settings - Fork 204
/
array_match.go
82 lines (66 loc) · 1.91 KB
/
array_match.go
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package matchers
import (
"strings"
"github.com/SpectoLabs/hoverfly/core/util"
)
const (
IgnoreUnknown = "ignoreUnknown"
IgnoreOrder = "ignoreOrder"
IgnoreOccurrences = "ignoreOccurrences"
)
var Array = "array"
func ArrayMatchWithoutConfig(match interface{}, toMatch string) bool {
return ArrayMatch(match, toMatch, nil)
}
func ArrayMatch(match interface{}, toMatch string, config map[string]interface{}) bool {
matchStringArr, ok := util.GetStringArray(match)
if !ok {
return false
}
toMatchArr := strings.Split(toMatch, ";")
ignoreUnknown := util.GetBoolOrDefault(config, IgnoreUnknown, false)
ignoreOrder := util.GetBoolOrDefault(config, IgnoreOrder, false)
ignoreOccurrences := util.GetBoolOrDefault(config, IgnoreOccurrences, false)
return (ignoreUnknown || hasAllKnown(matchStringArr, toMatchArr)) &&
(ignoreOccurrences || hasSameNoOfOccurrences(matchStringArr, toMatchArr)) &&
(ignoreOrder || isInSameOrder(matchStringArr, toMatchArr))
}
func hasSameNoOfOccurrences(matchGroup, toMatch []string) bool {
matchGroupSet := make(map[string]int)
for _, value := range matchGroup {
matchGroupSet[value] = matchGroupSet[value] + 1
}
toMatchSet := make(map[string]int)
for _, value := range toMatch {
toMatchSet[value] = toMatchSet[value] + 1
}
for key, value := range matchGroupSet {
if toMatchSet[key] != value {
return false
}
}
return true
}
func hasAllKnown(matchGroup, toMatch []string) bool {
matchGroupSet := make(map[string]bool)
for _, value := range matchGroup {
matchGroupSet[value] = true
}
for _, value := range toMatch {
if _, found := matchGroupSet[value]; !found {
return false
}
}
return true
}
func isInSameOrder(matchGroup, toMatch []string) bool {
index := 0
for _, value := range toMatch {
if index < len(matchGroup) && value == matchGroup[index] {
index++
} else if index == len(matchGroup) {
break
}
}
return index == len(matchGroup)
}