defmodule Colorify do import Bitwise @moduledoc """ This package generate color from binary. It can be used to style templates (HTML & CSS). """ @doc """ Generate `#FFFFFF` for empty string iex> Colorify.hex "#FFFFFF" """ def hex, do: "#FFFFFF" @doc """ Generate `#FFFFFF` for empty string iex> Colorify.hex "" "#FFFFFF" """ def hex(""), do: "#FFFFFF" @doc """ Generate hex color from binary iex> Colorify.hex("Elixir") "#DFD7E1" iex> Colorify.hex("Post title") "#F8B248" iex> Colorify.hex("Category") "#1E21DD" iex> Colorify.hex nil "#11AA01" iex> Colorify.hex true "#8E7536" iex> Colorify.hex false "#2319CB" """ def hex(string) do string |> do_hash |> do_hex end defp do_hash(string) do string |> to_charlist |> Enum.reduce(fn x, acc -> x + ((acc <<< 5) - acc ) end) end defp do_hex(hash) do list = Enum.map(0..2, &do_char(&1, hash)) ["#" | list] |> Enum.join end defp do_char(x, hash) do value = (hash >>> (x * 8)) &&& 0xFF "00" <> Integer.to_string(value, 16) |> String.slice(-2, 2) end end