I also do this reduce pattern that Michał Muskała put, though I often don't put a catch all and rather just error back invalid arguments as that usually means something was mis-typed and I want it reported early and fast.
On Monday, April 22, 2019 at 3:12:36 AM UTC-6, Michał Muskała wrote: > > 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, 胡永浩 <christo...@gmail.com <javascript:>>, > 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 elixir-l...@googlegroups.com <javascript:>. > To view this discussion on the web visit > https://groups.google.com/d/msgid/elixir-lang-core/11ef9a1a-1bbd-4ce3-93ff-3ad16466cb0e%40googlegroups.com > > <https://groups.google.com/d/msgid/elixir-lang-core/11ef9a1a-1bbd-4ce3-93ff-3ad16466cb0e%40googlegroups.com?utm_medium=email&utm_source=footer> > . > 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 elixir-lang-core+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/c06fd544-34d7-42e4-bf7b-2aab313c19de%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.