Skip to content

Instantly share code, notes, and snippets.

@gogocurtis
Created January 16, 2019 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gogocurtis/d85379b393ee141023865b8efcee34cc to your computer and use it in GitHub Desktop.
Save gogocurtis/d85379b393ee141023865b8efcee34cc to your computer and use it in GitHub Desktop.
# this is a cute pattern match
# get forms like
# $34.33
# 55
# €123
# €211
# 34 AUD
# 33 EUR
# etc
def convert_amount_str_to_currency_decimal(str) do
%{
"possible_currency_symbol" => currency_symbol_optional,
"expected_positive_decimal_number" => decimal_number_str,
"possible_currency_code" => currency_code_optional
} = capture_amount_parts(str)
%{
currency:
process_optional_currency_details(currency_symbol_optional, currency_code_optional),
decimal: Decimal.new(decimal_number_str),
raw: decimal_number_str
}
end
defp process_optional_currency_details(symbol, code) do
case [symbol, code] do
["$", ""] ->
"USD"
[_, code] ->
code
["£", _] ->
"GBP"
["€", _] ->
"EUR"
["", ""] -> # assume USD
"USD"
# let it crash on bad match
end
end
def valid_amount_str?(str) do
check_valid_amount_str(capture_amount_parts(str))
end
defp capture_amount_parts(str) do
Regex.named_captures(
~r/(?<possible_currency_symbol>\D*?)(?<expected_positive_decimal_number>\d{1,}(?:\.?\d{0,})?)(?<possible_currency_code>\D*?)/,
str
)
end
defp check_valid_amount_str(nil) do
false
end
defp check_valid_amount_str(a) when is_map(a) do
true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment