Skip to content

Commit d25eff3

Browse files
perf: use binary search in EnumRule
1 parent 5e7424e commit d25eff3

File tree

2 files changed

+22
-11
lines changed

2 files changed

+22
-11
lines changed

rule/enum.go

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package rule
22

33
import (
44
"fmt"
5+
"sort"
56

67
"github.com/conventionalcommit/commitlint/message"
78
)
@@ -26,7 +27,13 @@ func (r *ScopeEnumRule) Validate(msg *message.Commit) (string, bool) {
2627

2728
// SetAndCheckArgument sets the needed argument for the rule
2829
func (r *ScopeEnumRule) SetAndCheckArgument(arg interface{}) error {
29-
return setStringArrArg(&r.Scopes, arg, r.Name())
30+
err := setStringArrArg(&r.Scopes, arg, r.Name())
31+
if err != nil {
32+
return err
33+
}
34+
// sorting the string elements for binary search
35+
sort.Strings(r.Scopes)
36+
return nil
3037
}
3138

3239
// TypeEnumRule to validate types
@@ -49,5 +56,18 @@ func (r *TypeEnumRule) Validate(msg *message.Commit) (string, bool) {
4956

5057
// SetAndCheckArgument sets the needed argument for the rule
5158
func (r *TypeEnumRule) SetAndCheckArgument(arg interface{}) error {
52-
return setStringArrArg(&r.Types, arg, r.Name())
59+
err := setStringArrArg(&r.Types, arg, r.Name())
60+
if err != nil {
61+
return err
62+
}
63+
// sorting the string elements for binary search
64+
sort.Strings(r.Types)
65+
return nil
66+
}
67+
68+
func search(arr []string, toFind string) bool {
69+
ind := sort.Search(len(arr), func(i int) bool {
70+
return toFind <= arr[i]
71+
})
72+
return ind < len(arr) && arr[ind] == toFind
5373
}

rule/util.go

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -64,12 +64,3 @@ func toStringArr(arg interface{}, ruleName string) ([]string, error) {
6464
}
6565
return nil, fmt.Errorf("%s expects array of string value, but got %#v", ruleName, arg)
6666
}
67-
68-
func search(arr []string, toFind string) bool {
69-
for _, typ := range arr {
70-
if typ == toFind {
71-
return true
72-
}
73-
}
74-
return false
75-
}

0 commit comments

Comments
 (0)