Last active
January 27, 2020 13:27
-
-
Save tehprofessor/fd8aebeb4804201a49f37d99ba4c900c to your computer and use it in GitHub Desktop.
Elixir example for HN post
This file contains hidden or 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 Mapify | |
# This function uses a little trick matching on `%_{}` which matches only if data is a struct | |
def to_map(%_{} = data) do | |
container = Map.from_struct(data) | |
# Elixir will destructure a map into a two-item tuple {key, value}. | |
for {k, value} <- container, into: container, do: {k, to_map(value)} | |
end | |
# This matches `anything` it's the "catch all" for our `to_map` function | |
def to_map(data) do | |
data | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment