Created
October 18, 2014 00:20
-
-
Save BennyHallett/8d680a73f3f8b8219e07 to your computer and use it in GitHub Desktop.
ANSI Identicons in Elixir
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 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