Skip to content

Commit

Permalink
separately check if a pattern is wild
Browse files Browse the repository at this point in the history
  • Loading branch information
vodkaslime committed Sep 26, 2022
1 parent 8bdd9a1 commit d61fb49
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 7 deletions.
20 changes: 16 additions & 4 deletions wildcard.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package wildcard

import "strings"

type Matcher struct {
S byte
M byte
Expand All @@ -14,6 +12,21 @@ func NewMatcher() *Matcher {
}
}

func (m *Matcher) isWildPattern(pattern string) bool {
for i := range pattern {
c := pattern[i]
if c == m.M {
return true
}

if c == m.S {
return true
}
}

return false
}

func (m *Matcher) Match(pattern string, s string) (bool, error) {
// Edge cases.
if pattern == string(m.M) {
Expand All @@ -29,8 +42,7 @@ func (m *Matcher) Match(pattern string, s string) (bool, error) {

// If pattern does not contain wildcard chars, just compare the strings
// to avoid extra memory allocation.
if !strings.Contains(pattern, string(m.M)) &&
!strings.Contains(pattern, string(m.S)) {
if !m.isWildPattern(pattern) {
return pattern == s, nil
}

Expand Down
51 changes: 48 additions & 3 deletions wildcard_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,60 @@ import (
"github.com/stretchr/testify/assert"
)

type testCase struct {
type wildPatternTestCase struct {
p string
m bool
}

type matchTestCase struct {
p string
s string
m bool
}

func TestIsWildPattern(t *testing.T) {
testCases1 := []wildPatternTestCase{
{"*", true},
{"**", true},
{"*?", true},
{"?", true},
{".", false},
{"a", false},
{"a?c", true},
}

m1 := NewMatcher()
for _, tc := range testCases1 {
b := m1.isWildPattern(tc.p)
if !assert.Equal(t, b, tc.m) {
println(tc.p, tc.m)
}
}

testCases2 := []wildPatternTestCase{
{"*", true},
{"**", true},
{"*.", true},
{"?", false},
{".", true},
{"a", false},
{"a.c", true},
}

m2 := NewMatcher()
m2.S = '.'
for _, tc := range testCases2 {
b := m2.isWildPattern(tc.p)
if !assert.Equal(t, b, tc.m) {
println(tc.p, tc.m)
}
}

}

func TestMatch(t *testing.T) {

testCases1 := []testCase{
testCases1 := []matchTestCase{
{"", "", true},
{"*", "", true},
{"?", "", false},
Expand Down Expand Up @@ -43,7 +88,7 @@ func TestMatch(t *testing.T) {
m2 := NewMatcher()
m2.S = '.'

testCases2 := []testCase{
testCases2 := []matchTestCase{
{"", "", true},
{"*", "", true},
{".", "", false},
Expand Down

0 comments on commit d61fb49

Please sign in to comment.