Skip to content

Instantly share code, notes, and snippets.

@netikular
Last active December 24, 2015 01:16
Show Gist options
  • Save netikular/4b05f9340b8ff81ba773 to your computer and use it in GitHub Desktop.
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
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
@netikular
Copy link
Author

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment