Skip to content

Instantly share code, notes, and snippets.

@joshnuss
Created July 15, 2014 14:37
Show Gist options
  • Save joshnuss/885c3e5ff61607d6dbf2 to your computer and use it in GitHub Desktop.
Save joshnuss/885c3e5ff61607d6dbf2 to your computer and use it in GitHub Desktop.
Find credit card type using pattern matching
# usage:
#
# iex> CreditCard.type(%{number: "4242424242424242"})
# => :visa
defmodule CreditCard do
defstruct [:number, :expiration, :cvc]
# find the type of a credit card
# attempt map for first character, first 2 characters, etc (up to 4 characters)
# when no match found return :unknown
def type(%{number: number}) do
Enum.find_value(1..4, &(map(number, &1))) || :unknown
end
# slice number, covert to integer and re-map
defp map(number, length) do
number
|> String.slice(0, length)
|> String.to_integer
|> map
end
defp map(4), do: :visa
defp map(n) when n in 51..55, do: :master
defp map(n) when n in [34, 37], do: :amex
defp map(n) when n in 300..305 or n in [36, 38], do: :diners
defp map(n) when n in [6011, 65], do: :discover
defp map(n) when n in [2131, 1800, 35], do: :jcb
defp map(_), do: nil
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment