-
Notifications
You must be signed in to change notification settings - Fork 33
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #48 from mykewould/deep_key_change
Recursive key change for Maps
- Loading branch information
Showing
2 changed files
with
32 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
defmodule Crutches.Map do | ||
@doc ~S""" | ||
Recursively traverse a (nested) hash and change the keys based on | ||
the function provided. | ||
## Examples | ||
iex> map = %{"hello" => %{"goodbye" => 1}, "akuna" => "matata"} | ||
iex> Map.dkeys_update(map, fn (key) -> String.to_atom(key) end) | ||
%{:hello => %{:goodbye => 1}, :akuna => "matata"} | ||
iex> map = %{"hello" => %{"goodbye" => 1, "akuna" => "matata", "hello" => %{"goodbye" => 1, "akuna" => "matata"}}, "akuna" => "matata"} | ||
iex> Map.dkeys_update(map, fn (key) -> String.to_atom(key) end) | ||
%{hello: %{akuna: "matata", goodbye: 1, hello: %{akuna: "matata", goodbye: 1}}, akuna: "matata"} | ||
""" | ||
def dkeys_update(map, fun), do: dkeys_update(map, fun, %{}) | ||
def dkeys_update(map, _, acc) when map == %{}, do: acc | ||
def dkeys_update(map, fun, acc) do | ||
key = Map.keys(map) |> List.first | ||
case is_map(map[key]) do | ||
true -> value = dkeys_update(map[key], fun) | ||
_ -> value = map[key] | ||
end | ||
dkeys_update(Map.delete(map, key), fun, Map.put(acc, fun.(key), value)) | ||
end | ||
end |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
defmodule Crutches.MapTest do | ||
alias Crutches.Map | ||
use ExUnit.Case, async: true | ||
doctest Crutches.Map | ||
end |