Skip to content

Commit

Permalink
feat: find alpha2 by currency
Browse files Browse the repository at this point in the history
  • Loading branch information
perriea committed Jul 19, 2022
1 parent 2fa96f5 commit 33d4a30
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
15 changes: 15 additions & 0 deletions query.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type Query struct {
Alpha3ToAlpha2 map[string]string
NativeNameToAlpha2 map[string]string
CallingCodeToAlpha2 map[string]string
CurrencyToAlpha2 map[string][]Country
}

// FindCountryByName finds a country by given name
Expand Down Expand Up @@ -67,6 +68,20 @@ func (q *Query) FindCountryByCallingCode(callingCode string) (result Country, er
return q.Countries[alpha2], nil
}

// FindCountriesByCurrency finds a Country based on the given struct data
func (q *Query) FindCountriesByCurrency(currency string) (results []Country, err error) {
if len(currency) != 3 {
return nil, makeError("Invalid currency format", currency)
}

alpha2, exists := q.CurrencyToAlpha2[currency]
if !exists {
return []Country{}, makeError("Could not find countries with currency name", currency)
}

return alpha2, nil
}

// FindAllCountries returns a list of all countries
func (q *Query) FindAllCountries() (countries map[string]Country) {
return q.Countries
Expand Down
12 changes: 12 additions & 0 deletions setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ func NewFromPath(dataPath string) *Query {
queryInstance.Alpha3ToAlpha2 = populateAlphaIndex(queryInstance.Countries)
queryInstance.NativeNameToAlpha2 = populateNativeNameIndex(queryInstance.Countries)
queryInstance.CallingCodeToAlpha2 = populateCallingCodeIndex(queryInstance.Countries)
queryInstance.CurrencyToAlpha2 = populateCallingCurrencyIndex(queryInstance.Countries)

subdivisions := populateSubdivisions(dataPath)
for k := range queryInstance.Countries {
Expand Down Expand Up @@ -220,3 +221,14 @@ func populateCallingCodeIndex(countries map[string]Country) map[string]string {
}
return index
}

func populateCallingCurrencyIndex(countries map[string]Country) map[string][]Country {
index := make(map[string][]Country)

for _, country := range countries {
for _, currency := range country.Currencies {
index[currency] = append(index[currency], country)
}
}
return index
}

0 comments on commit 33d4a30

Please sign in to comment.