Skip to content

Commit

Permalink
optimize Pattern.WeakEqual
Browse files Browse the repository at this point in the history
  • Loading branch information
apetruhin committed Nov 20, 2023
1 parent bbcd7a7 commit 1e9e775
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
16 changes: 8 additions & 8 deletions pattern.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,16 @@ func (p *Pattern) WeakEqual(other *Pattern) bool {
if len(p.words) != len(other.words) {
return false
}
var matches int
for i, op := range other.words {
if p.words[i] == op {
matches++
var diffs int
for i, ow := range other.words {
if p.words[i] != ow {
diffs++
if diffs > 1 {
return false
}
}
}
if matches >= len(p.words)-1 {
return true
}
return false
return true
}

func NewPattern(input string) *Pattern {
Expand Down
8 changes: 8 additions & 0 deletions pattern_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,14 @@ func TestPatternWeakEqual(t *testing.T) {
assert.False(t, NewPattern("foo bar baz").WeakEqual(NewPattern("baz bar foo")))
}

func BenchmarkPatternWeakEqual(b *testing.B) {
p1 := NewPattern("foo one two bar buz")
p2 := NewPattern("foo three four bar buz")
for n := 0; n < b.N; n++ {
p1.WeakEqual(p2)
}
}

func TestPatternRemoveQuotedAndBrackets(t *testing.T) {
assert.Equal(t, "foo bar", removeQuotedAndBrackets(`foo 'squoted' bar`))
assert.Equal(t, "foo bar", removeQuotedAndBrackets(`foo 'squoted \'baz\'' bar`))
Expand Down

0 comments on commit 1e9e775

Please sign in to comment.