In Elixir, what would be an efficient way to filter a Map
by its values.
Right now I have the following solution
%{foo: \"bar\", biz: ni
It could be a little expensive but it is more declarative, which IMO adds more value. Also consider how big is going to be your collection and if it makes sense to optimize this filter.
However, I understand your concern, so here is what I did:
%{foo: "bar", biz: nil, baz: 4}
|> Enum.reduce(%{}, filter_nil_values/2)
Where filter_nil_values/2
is defined as
defp filter_nil_values({_k, nil}, accum), do: accum
defp filter_nil_values({k, v}, accum), do: Map.put(accum, k, v)
I tried to do this in a one-line function, but it looks awful.