Skip to content

Instantly share code, notes, and snippets.

@iffyuva
Last active January 13, 2019 13:34
Show Gist options
  • Save iffyuva/6dbc3d3657e5b1e585c2ce2d53b6c973 to your computer and use it in GitHub Desktop.
Save iffyuva/6dbc3d3657e5b1e585c2ce2d53b6c973 to your computer and use it in GitHub Desktop.
elixir pattern matching fun

Its very easy to refactor nested code like this in elixir. if/else can be easily pattern matched

defp check_operation(operation) do
  if operation.done do
    if operation.error do
      {:error, "Something went wrong in GCP"}
    else
      {:ok, "Project creation successful"}
    end
  else
    {:error, :retry}
  end
end

Each and every if else can be transformed into a separate function call. So, above code can be written as:

defp check_operation(%{done: true} = operation) do
  if operation.error do
    {:error, "Something went wrong in GCP"}
  else
    {:ok, "Project creation successful"}
  end
end

defp check_operation(operation) do
  {:error, :retry}
end

This can be further broken down into this:

defp check_operation(%{done: true, error: true}) do
  {:error, "Something went wrong in GCP"}
end

defp check_operation(%{done: true} do
  {:ok, "Project creation successful"}
end

defp check_operation(_operation) do
  {:error, :retry}
end
@goromlagche
Copy link

goromlagche commented Jan 13, 2019

another code golf 😄

check_operation = fn
  %{done: true, error: true} -> {:error, "Something went wrong in GCP"}
  %{done: true} -> {:ok, "Project creation successful"}
  _ -> {:error, :retry}
end

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