Skip to content

Instantly share code, notes, and snippets.

@rsgrafx
Created July 27, 2018 16:50
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 rsgrafx/dd327bf297e21203b25eb6f3fcf9ce58 to your computer and use it in GitHub Desktop.
Save rsgrafx/dd327bf297e21203b25eb6f3fcf9ce58 to your computer and use it in GitHub Desktop.
defmodule Flattery do
def run({a, b}, acc)
when is_map(b) == false,
do: Map.merge(acc, %{a => b})
def run({_a, b}, acc)
when is_map(b),
do: go(b, acc)
def run({a, b}, acc),
do: Map.merge(acc, %{a => b})
def go(enum, acc \\ %{})
def go(enum, acc) do
Enum.reduce(enum, acc, &run/2)
end
end
@rsgrafx
Copy link
Author

rsgrafx commented Jul 27, 2018

Sometimes we forget things. Is there an existing function on Map or Enum to flatten a map with many nested maps.

#> Flattery.go(%{foo: %{bar: 1, baz: %{bingo: 2, basic: %{zed: 3}}}})
#> %{bar: 1, bingo: 2, zed: 3}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment