currency.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package unit
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. type Currency string
  7. const (
  8. AUD Currency = "AUD"
  9. BRL Currency = "BRL"
  10. CAD Currency = "CAD"
  11. CHF Currency = "CHF"
  12. CNY Currency = "CNY"
  13. DKK Currency = "DKK"
  14. EUR Currency = "EUR"
  15. GBP Currency = "GBP"
  16. IDR Currency = "IDR"
  17. INR Currency = "INR"
  18. JPY Currency = "JPY"
  19. NOK Currency = "NOK"
  20. PLN Currency = "PLN"
  21. SEK Currency = "SEK"
  22. USD Currency = "USD"
  23. )
  24. // validCurrencies is a map of all valid currency codes for quick lookup
  25. var validCurrencies = map[string]Currency{
  26. string(AUD): AUD,
  27. string(BRL): BRL,
  28. string(CAD): CAD,
  29. string(CHF): CHF,
  30. string(CNY): CNY,
  31. string(DKK): DKK,
  32. string(EUR): EUR,
  33. string(GBP): GBP,
  34. string(IDR): IDR,
  35. string(INR): INR,
  36. string(JPY): JPY,
  37. string(NOK): NOK,
  38. string(PLN): PLN,
  39. string(SEK): SEK,
  40. string(USD): USD,
  41. }
  42. // ParseCurrency parses a string into a Currency type.
  43. // It performs case-insensitive matching and returns an error if the string
  44. // does not match any valid currency code.
  45. func ParseCurrency(s string) (Currency, error) {
  46. upper := strings.ToUpper(s)
  47. if currency, ok := validCurrencies[upper]; ok {
  48. return currency, nil
  49. }
  50. return "", fmt.Errorf("invalid currency: %q", s)
  51. }