-
-
Save zporter/1c31d4181c370c5fe09d3e66c574add5 to your computer and use it in GitHub Desktop.
Elixir: Parsing initials of a given name
This file contains hidden or 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
iex(2)> c "name.ex" | |
[Name] | |
iex(3)> Name.initials("Cher") | |
"C" | |
iex(4)> Name.initials("Barry Bluejeans") | |
"BB" | |
iex(5)> Name.initials("Jean-Claude Van Damme") | |
"JVD" |
This file contains hidden or 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 Name do | |
def initials(name) when name in [nil, ""], do: "?" | |
def initials(name) when is_binary(name) do | |
name | |
|> String.split(" ") | |
|> extract_initials() | |
end | |
defp extract_initials([]), do: "" | |
defp extract_initials([name_part | name_parts]) do | |
String.slice(name_part, 0, 1) <> extract_initials(name_parts) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment