Created
February 5, 2017 20:06
-
-
Save dimitarvp/26551dfedbe53735efe3a07d521f2a49 to your computer and use it in GitHub Desktop.
Elixir function modifying a destination map only if a source map has a certain key whose value is processed and stored in the destination map.
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 Play do | |
def test1 do | |
src = %{createdAt: "2017-01-19T08:32:26+02:00"} | |
dest = %{} | |
dest = | |
case Map.has_key?(src, :createdAt) do | |
true -> | |
{:ok, date, _} = DateTime.from_iso8601(src[:createdAt]) | |
Map.put(dest, :createdAt, date) | |
false -> | |
dest | |
end | |
dest | |
end | |
end | |
Play.test1 |
defmodule Play do
def test1 do
src = %{createdAt: "2017-01-19T08:32:26+02:00"}
dest = %{}
case src[:createdAt] do
nil -> dest
createdAt ->
{ :ok, date, _ } = DateTime.from_iso8601(createdAt)
Map.put(dest, :createdAt, date)
end
end
end
or even better:
defmodule Play do
def test(%{:createdAt => createdAt} = src, dest) do
{ :ok, date, _ } = DateTime.from_iso8601(createdAt)
Map.put(dest, :createdAt, date)
end
def test(_, dest), do: dest
end
Thanks @talentdeficit. Ended up slightly adapting a suggestion from Ben Wilson: https://www.irccloud.com/pastebin/mZJhLJLa/
EDIT: pasting in case the link stops working:
map = %{created_at: "2017-01-19T08:32:26+02:00", updated_at: "2017-01-19T08:32:26+02:00"}
converted = Map.new(map, fn
{key, created_at} when key in [:created_at, :updated_at] ->
{key, DateTime.from_iso8601!(created_at)}
other ->
other
end)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This works just fine. My question is can this be written more concisely? Can it be written in a manner that allows piping as well?