cjm2671
cjm2671

Reputation: 19476

Interpolating Map Keys with Elixir

r = Date.range(~D[2019-07-01], ~D[2019-07-31])
q =
    %{
      ~D[2019-07-22] => 387,
      ~D[2019-07-23] => 256,
      ~D[2019-07-24] => 117,
      ~D[2019-07-25] => 1
    }

I've got a date range enumerable, and I'm trying to add date => 0 for every date that isn't present in q.

This would be easy with a for loop, but that's not an option. I tried various Enum.map functions, I'm pretty sure that's not what I want. I think I want to be using reduce, but I'm not certain.

How do I approach this?

Thanks!

Upvotes: 0

Views: 219

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Use Map.put_new/3:

Enum.reduce(r, q, &Map.put_new(&2, &1, 0))

Less performant version (it looks up the map on every iteration) with Kernel.SpecialForms.for/1 comprehension:

for date <- r, do: {date, Map.get(q, date, 0)}, into: %{} 

Upvotes: 2

Related Questions