Skip to content

Commit

Permalink
Added lookup tables instead of iterating the array
Browse files Browse the repository at this point in the history
  • Loading branch information
Ferdy Pruis committed Mar 23, 2021
1 parent 7104c3c commit 68da37d
Show file tree
Hide file tree
Showing 3 changed files with 780 additions and 12 deletions.
18 changes: 6 additions & 12 deletions country.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,32 +19,26 @@ func (c Country) Name() string { return countries[c].name }
// FromAlpha2 returns Country for the two-letter alpha2 code.
// Or an error if it does not exist.
func FromAlpha2(alpha2 string) (Country, error) {
for c, country := range countries {
if country.alpha2 == alpha2 {
return Country(c), nil
}
if c, ok := fromAlpha2[alpha2]; ok {
return c, nil
}
return Country(0), Error("no country exists with alpha2-code " + alpha2)
}

// FromAlpha3 returns Country for the three-letter alpha3 code.
// Or an error if it does not exist.
func FromAlpha3(alpha3 string) (Country, error) {
for c, country := range countries {
if country.alpha3 == alpha3 {
return Country(c), nil
}
if c, ok := fromAlpha3[alpha3]; ok {
return c, nil
}
return Country(0), Error("no country exists with alpha3-code " + alpha3)
}

// FromNumeric returns Country for the three-digit numeric code.
// Or an error if it does not exist.
func FromNumeric(numeric string) (Country, error) {
for c, country := range countries {
if country.numeric == numeric {
return Country(c), nil
}
if c, ok := fromNumeric[numeric]; ok {
return c, nil
}
return Country(0), Error("no country exists with numeric-code " + numeric)
}
Expand Down
Loading

0 comments on commit 68da37d

Please sign in to comment.