Skip to content

Commit

Permalink
Merge pull request #5 from Clarilab/add-exists-check
Browse files Browse the repository at this point in the history
feat: add exists check
  • Loading branch information
nicoandrewss authored Aug 8, 2024
2 parents b809e41 + 8275cd5 commit 30592db
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 5 deletions.
59 changes: 54 additions & 5 deletions countries.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,32 @@ import (
"strings"
)

const (
alpha2Len = 2
alpha3Len = 3
)

// AllMappings returns the list of all country mappings.
func AllMappings() []Mapping {
return mappings
}

// Exists checks if any occurrence of the query matches.
func Exists(query string) bool {
switch {
case len(query) < alpha2Len:
return false
case len(query) == alpha2Len:
return existsByAlpha2(query)
case len(query) == alpha3Len:
return existsByAlpha3(query)
default:
return existsByNameOrNationality(query)
}
}

// FindCountry looks up any matching occurrence of the query.
func FindCountry(query string) (*Mapping, error) {
const (
alpha2Len = 2
alpha3Len = 3
)

switch {
case len(query) < alpha2Len:
return nil, ErrCountryNotFound
Expand Down Expand Up @@ -63,6 +77,41 @@ func findCountryByNameOrNationality(query string) (*Mapping, error) {
return nil, ErrCountryNotFound
}

func existsByAlpha2(query string) bool {
query = strings.ToUpper(query)

for i := range mappings {
if mappings[i].Alpha2 == query {
return true
}
}

return false
}

func existsByAlpha3(query string) bool {
query = strings.ToUpper(query)

for i := range mappings {
if mappings[i].Alpha3 == query {
return true
}
}

return false
}

func existsByNameOrNationality(query string) bool {
for i := range mappings {
if isCountryNameOrNationality(mappings[i].Translations[EN], query) ||
isCountryNameOrNationality(mappings[i].Translations[DE], query) {
return true
}
}

return false
}

func isCountryNameOrNationality(translation Translation, query string) bool {
return strings.EqualFold(translation.Common, query) ||
strings.EqualFold(translation.Official, query) ||
Expand Down
26 changes: 26 additions & 0 deletions countries_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,32 @@ func TestAlpha2(t *testing.T) {
}
}

func Test_Exists(t *testing.T) {
t.Run("exists by country name", func(t *testing.T) {
if !countries.Exists("Australia") {
t.Error("expected: true, got: false")
}
})

t.Run("exists by alpha 2", func(t *testing.T) {
if !countries.Exists("AU") {
t.Error("expected: true, got: false")
}
})

t.Run("exists by alpha 3", func(t *testing.T) {
if !countries.Exists("AUS") {
t.Error("expected: true, got: false")
}
})

t.Run("does not exist", func(t *testing.T) {
if countries.Exists("NonexistentCountry") {
t.Error("expected: false, got: true")
}
})
}

func BenchmarkGetByCountryName(b *testing.B) {
b.ReportAllocs()

Expand Down

0 comments on commit 30592db

Please sign in to comment.