In a case like this, I usually prefer to flip the task around and reduce over 
the params:

Enum.reduce(params, %{type: nil}, fn
  {"language", language}, acc -> Map.put(acc, :language, language)
  {"id", id}, acc -> Map.put(acc, :id, id)
  {"type", type}, acc -> Map.put(acc, :type, type)
  _, acc -> acc
end)

It works nice and doesn't require any conditionals. I saw the double negation - 
if that's important for the logic, it could be achieved by adding in `when 
language not in [nil, false]`, which could be further reduced to a nice `when 
truthy(language)` defguard macro.

Michał.
On 22 Apr 2019, 10:26 +0200, 胡永浩 <[email protected]>, wrote:
> I am now doing it like this in a route:
>    query = %{ type: params["type"] }
>    query = if !!params["language"], do: Map.put(query, :language, 
> params["language"]), else: query
>    query = if !!params["id"], do: Map.put(query, :language, params["id"]), 
> else: query
> I wonder, could we afford a function to decide whether to put the key?(I do 
> mention this as a proposal if there is no best practice.)
>
> RIP, Joe.
>
>
> --
> You received this message because you are subscribed to the Google Groups 
> "elixir-lang-core" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to [email protected].
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/elixir-lang-core/11ef9a1a-1bbd-4ce3-93ff-3ad16466cb0e%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups 
"elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/elixir-lang-core/4052719e-1bda-4d53-96c9-26f0e385a599%40Spark.
For more options, visit https://groups.google.com/d/optout.

Reply via email to