Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ANSI Identicons in Elixir
defmodule Identicon do
def make(username) do
username
|> encode
|> draw
end
defp encode(username) do
:crypto.md5(username)
|> select_colour
|> select_alpha
end
defp select_colour(md5), do: _select_colour(md5 |> :binary.bin_to_list)
defp _select_colour([ r, g, b | tail ]), do: { { r, g, b }, tail ++ tail }
defp select_alpha({ { r,g,b }, [a|tail] }), do: { { r, g, b, a }, tail }
defp draw({_, []}), do: nil
defp draw({_, [a, b, c, d, e | tail]}) do
expand([a, b, c, d, e])
|> map_colours
|> render
draw({nil, tail})
end
defp expand(array), do: Enum.flat_map(array, &([&1, &1, &1, &1, &1]))
defp map_colours(array), do: Enum.map(array, &(choose_colour(&1)))
defp choose_colour(colour) when colour < 86, do: :red_background
defp choose_colour(colour) when colour < 172, do: :green_background
defp choose_colour(_), do: :blue_background
defp render(array) do
Enum.flat_map(array, &([&1, " "]))
|> IO.ANSI.format(true)
|> draw_three
end
defp draw_three(string) do
IO.puts(string)
IO.puts(string)
IO.puts(string)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.