Skip to content

Instantly share code, notes, and snippets.

@rylev
Created April 8, 2014 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rylev/10194344 to your computer and use it in GitHub Desktop.
Save rylev/10194344 to your computer and use it in GitHub Desktop.
Small Module For Parsing and Encoding RGB Values
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