Skip to content

Instantly share code, notes, and snippets.

@Geekfish
Created August 11, 2022 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Geekfish/54987a2165ef6a4808893db97128cdd0 to your computer and use it in GitHub Desktop.
Save Geekfish/54987a2165ef6a4808893db97128cdd0 to your computer and use it in GitHub Desktop.
ExMachina Formatters
defmodule ExMachina.Sequence.Formatters do
@moduledoc false
@latin_letters 26
@codepoint_start 65
@spec to_alpha_code(integer(), integer()) :: String.t()
@doc """
Converts an integer (like a sequence counter) to an n-letter uppercase code.
Examples:
iex> Formatters.to_alpha_code(5)
"AAE"
iex> Formatters.to_alpha_code(500)
"ATF"
iex> Formatters.to_alpha_code(5000000)
"MLR"
iex> Formatters.to_alpha_code(5, 2)
"AE"
"""
def to_alpha_code(counter, code_length \\ 3) do
counter_to_alpha =
(counter - 1)
# Convert our integer to base-26 (number of letters in the latin alphabet)
|> Integer.digits(@latin_letters)
# Shift the resulting digits so they match the codepoints of the alphabet
|> Enum.map(&(&1 + @codepoint_start))
# Prefix with As to ensure we have at least `code_length` chars
['A']
|> List.duplicate(code_length - 1)
|> Kernel.++(counter_to_alpha)
# If our chars are too many, just take the last `code_length` chars.
|> Enum.take(-code_length)
|> to_string()
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment