Created
April 8, 2014 21:20
-
-
Save rylev/10194344 to your computer and use it in GitHub Desktop.
Small Module For Parsing and Encoding RGB Values
This file contains hidden or 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 RGB do | |
import Enum, only: [map: 2, join: 1, filter: 2, chunk: 2, count: 1] | |
def encode(rgb) when is_list rgb do | |
hex = rgb |> | |
map(&(integer_to_list &1, 16)) |> | |
map(fn [x] -> [x, x]; x -> x end) |> | |
map(&String.from_char_list!/1) |> | |
join | |
"#" <> hex | |
end | |
def decode(rgb_string) when is_binary rgb_string do | |
rgb_string |> | |
rgb_hex |> | |
String.split("") |> | |
filter(&(&1 != "")) |> | |
fn list -> chunk(list, div(count(list), 3)) end.() |> | |
map(&join/1) |> | |
map(&(binary_to_integer &1, 16)) | |
end | |
defp rgb_hex("#" <> rest), do: rest | |
defp rgb_hex("0x" <> rest), do: rest | |
defp rgb_hex(full), do: full | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment