Created
August 28, 2016 15:45
-
-
Save mattsnyder/987b414353c3b0d7d04d089be625e218 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Phone do | |
@doc """ | |
Remove formatting from a phone number. | |
Returns "0000000000" if phone number is not valid | |
(10 digits or "1" followed by 10 digits) | |
## Examples | |
iex> Phone.number("123-456-7890") | |
"1234567890" | |
iex> Phone.number("+1 (303) 555-1212") | |
"3035551212" | |
iex> Phone.number("867.5309") | |
"0000000000" | |
""" | |
@spec number(String.t) :: String.t | |
def number(raw) do | |
raw | |
|> to_char_list | |
|> :phone_number_lexer.string | |
|> check_length | |
|> simple_number | |
end | |
defp check_length({:ok, [{:int, 1, '1'}|rest], _}) when length(rest) == 10, do: {:ok, rest, nil} | |
defp check_length({:ok, tokens, _}) when length(tokens) == 10, do: {:ok, tokens, nil} | |
defp check_length({:error, tokens, _}), do: {:error, tokens, nil} | |
defp check_length({:ok, tokens, _}), do: {:error, tokens, nil} | |
defp simple_number({:error, _, _}), do: "0000000000" | |
defp simple_number({:ok, tokens, _}) do | |
tokens | |
|> Enum.map(fn({:int, _, digit}) -> digit end) | |
|> Enum.join("") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment