Last active
December 24, 2015 01:16
-
-
Save netikular/4b05f9340b8ff81ba773 to your computer and use it in GitHub Desktop.
Increment A to B or ZZ to AAA - only works on capitol ASCII letters
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 Tallyj.StringExtensions do | |
@moduledoc """ | |
This module provides a function that will take a uppercase ASCII letter and | |
return the next logical value. Wrapping back to A when Z is provided. | |
Examples: | |
next("A") | |
=> "B" | |
next("QA") | |
=> "QB" | |
next("QZ") | |
=> "RA" | |
""" | |
def next(string) when is_binary(string) do | |
val = next(string |> String.to_char_list |> Enum.reverse, []) | |
to_string(val |> Enum.reverse) | |
end | |
defp next([letter | rest], acc) do | |
new_letter = next_letter(letter) | |
next({new_letter, Enum.count(rest)}, rest, acc) | |
end | |
defp next([], acc) do | |
acc | |
end | |
defp next({65, 0}, rest, acc), do: next(rest, [[65, 65] | acc]) | |
defp next({65, _}, rest, acc), do: next(rest, [65 | acc]) | |
defp next({ltr, _}, rest, acc), do: [[ltr | acc] | rest] | |
defp next_letter(value) when value >= 90, do: 65 | |
defp next_letter(value), do: value + 1 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I tried with this version to be a little more pattern match with functions instead of a case. Logically still the same but implementation is quite different?