Created
August 11, 2022 12:38
-
-
Save Geekfish/54987a2165ef6a4808893db97128cdd0 to your computer and use it in GitHub Desktop.
ExMachina Formatters
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 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