Created
July 29, 2015 11:31
-
-
Save elixirplayground/f9da12ecf5c7e770c86a to your computer and use it in GitHub Desktop.
elixirplayground.com code share
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 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