Skip to content

Instantly share code, notes, and snippets.

@joladev
Last active August 15, 2019 05:40
Show Gist options
  • Save joladev/7af4d3d654f3320526ccc50fe91c8b28 to your computer and use it in GitHub Desktop.
Save joladev/7af4d3d654f3320526ccc50fe91c8b28 to your computer and use it in GitHub Desktop.
@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