Skip to content

Instantly share code, notes, and snippets.

@elixirplayground
Created July 29, 2015 11:31
Show Gist options
  • Save elixirplayground/f9da12ecf5c7e770c86a to your computer and use it in GitHub Desktop.
Save elixirplayground/f9da12ecf5c7e770c86a to your computer and use it in GitHub Desktop.
elixirplayground.com code share
defmodule Crutches.Map do
def deep_key_change(map, fun), do: deep_key_change(map, fun, %{})
def deep_key_change(map, _, acc) when map == %{}, do: acc
def deep_key_change(map, fun, acc) do
map
|> Enum.reduce acc, fn(submap, akk) ->
case submap do
{key, value} when is_map(value) ->
Map.put(akk, fun.(key), deep_key_change(value, fun, %{}))
{key, value} ->
Map.put(akk, fun.(key), value)
end
end
end
end
map1 = %{"hello" => %{"goodbye" => 1}, "akuna" => "matata"}
map2 = %{"hello" => %{"goodbye" => 1, "akuna" => "matata", "hello" => %{"goodbye" => 1, "akuna" => "matata"}}, "akuna" => "matata"}
map1 |> Crutches.Map.deep_key_change(fn(key) -> String.to_atom(key) end) |> inspect |> IO.puts
map2 |> Crutches.Map.deep_key_change(fn(key) -> String.to_atom(key) end) |> inspect |> IO.puts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment