Created
November 21, 2018 10:04
-
-
Save jalberto/ebf77f3fdf34bc202de3e453d616ae38 to your computer and use it in GitHub Desktop.
Small util to transform Map keys into atoms or strings
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 MyApp.MapUtils do | |
@doc ~S""" | |
Transform keys in a Map to atoms | |
## Examples | |
iex> MyApp.Maputils.map_keys_to_atoms(%{"foo" => 1, "bar" => %{foo2: "2"}}) | |
{bar: %{foo2: "2"}, foo: 1} | |
""" | |
def map_keys_to_atoms(map) when is_map(map) do | |
for {key, val} <- map, into: %{} do | |
{atomise(key), traverse(val, :atm)} | |
end | |
end | |
@doc ~S""" | |
Transform keys in a Map to strings | |
## Examples | |
iex> MyApp.Maputils.map_keys_to_strings(%{foo: 1, bar: %{"foo2" => "2"}}) | |
{"bar": %{"foo2": "2"}, "foo": 1} | |
""" | |
def map_keys_to_strings(map) when is_map(map) do | |
for {key, val} <- map, into: %{} do | |
{stringfy(key), traverse(val, :str)} | |
end | |
end | |
# Make sure we know what output we want | |
defp traverse(item, :str) when is_map(item), do: map_keys_to_strings(item) | |
defp traverse(item, :atm) when is_map(item), do: map_keys_to_atoms(item) | |
defp traverse(item) when is_map(item), do: map_keys_to_strings(item) | |
defp traverse(item, _), do: item | |
defp stringfy(item) do | |
cond do | |
is_atom(item) -> Atom.to_string(item) | |
true -> item | |
end | |
end | |
defp atomise(item) do | |
cond do | |
is_bitstring(item) -> String.to_atom(item) | |
true -> item | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment