Last active
August 15, 2019 05:40
-
-
Save joladev/7af4d3d654f3320526ccc50fe91c8b28 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
@alphabet_lower ?a..?z | |
@alphabet_upper ?A..?Z | |
@spec rotate(text :: String.t(), shift :: integer) :: String.t() | |
def rotate(text, shift) do | |
text | |
|> String.to_charlist() | |
|> Enum.map(&(rot(&1, shift))) | |
|> List.to_string() | |
end | |
defp rot(char, shift) when char in @alphabet_lower do | |
rot(char, shift, @alphabet_lower) | |
end | |
defp rot(char, shift) when char in @alphabet_upper do | |
rot(char, shift, @alphabet_upper) | |
end | |
defp rot(char, _), do: char | |
defp rot(char, shift, alphabet) do | |
case Enum.find_index(alphabet, & &1 == char) do | |
nil -> raise ArgumentError | |
index -> Enum.at(alphabet, Integer.mod(index + shift, 26)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment