Last active
March 6, 2017 19:59
-
-
Save martijn/3f49246cf4194da3783f8c0c86da8dc1 to your computer and use it in GitHub Desktop.
An example of writing proper Elixir code instead of Ruby code in Elixir
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
# Iteration 1: This is basically writing Ruby in Elixir | |
params = %{"name" => "Foobar", "time" => %{"hour" => "8", "minute" => "30"}} | |
defmodule Example do | |
def cast_times_to_minutes(params, fields) do | |
Enum.map(params, fn({key, value}) -> | |
if Enum.member?(fields, key) && is_map(value) do | |
{key, time_to_minutes(value)} | |
else | |
{key, value} | |
end | |
end) | |
|> Map.new | |
end | |
def time_to_minutes(time) do | |
String.to_integer(time["hour"]) * 60 + String.to_integer(time["minute"]) | |
end | |
end | |
Example.cast_times_to_minutes(params, ["time"]) | |
# => %{"name" => "Foobar", "time" => 510} |
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
# Iteration 2: Apply a list comprehension and some pattern matching | |
params = %{"name" => "Foobar", "time" => %{"hour" => "8", "minute" => "30"}} | |
defmodule Example do | |
def cast_times_to_minutes(params, fields) do | |
for {key, value} <- params, into: %{} do | |
if Enum.member?(fields, key) && is_map(value) do | |
{key, time_to_minutes(value)} | |
else | |
{key, value} | |
end | |
end | |
end | |
def time_to_minutes(%{"hour" => hour, "minute" => minute}) do | |
String.to_integer(hour) * 60 + String.to_integer(minute) | |
end | |
end | |
Example.cast_times_to_minutes(params, ["time"]) | |
# => %{"name" => "Foobar", "time" => 510} |
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
# Iteration 3: Go full Elixir; find the time fields by filtering in the list comprehension, merge back into the rest | |
params = %{"name" => "Foobar", "time" => %{"hour" => "8", "minute" => "30"}} | |
defmodule Example do | |
def cast_times_to_minutes(params) do | |
Map.merge(params, | |
for {key, %{"hour" => hour, "minute" => minute}} <- params, into: %{} do | |
{key, String.to_integer(hour) * 60 + String.to_integer(minute)} | |
end) | |
end | |
end | |
Example.cast_times_to_minutes(params) | |
# => %{"name" => "Foobar", "time" => 510} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment