Skip to content

Instantly share code, notes, and snippets.

@dimitarvp
Created February 5, 2017 20:06
Show Gist options
  • Save dimitarvp/26551dfedbe53735efe3a07d521f2a49 to your computer and use it in GitHub Desktop.
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.
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
@dimitarvp
Copy link
Author

dimitarvp commented Feb 5, 2017

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?

@talentdeficit
Copy link

talentdeficit commented Feb 5, 2017

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

@dimitarvp
Copy link
Author

dimitarvp commented Feb 5, 2017

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