Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map with indifferent key access

Tags:

elixir

What is the best practice to match on a Map with keys defined as either atoms or strings?

%{"artist" => artist, "track" => track, "year" => year}

vs

%{artist: artist, track: track, year: year}

Function needs to match on both:

def duplicate_post(%{"artist" => artist, "track" => track, "year" => year}) do
  ...
end
like image 742
Midwire Avatar asked Mar 12 '23 13:03

Midwire


2 Answers

The best way I can think of is to define the function twice, once for each kind of input, and call one of them from the other.

def duplicate_post(%{"artist" => artist, "track" => track, "year" => year}) do
  duplicate_post(%{artist: artist, track: track, year: year})
end

def duplicate_post(%{artist: artist, track: track, year: year}) do
  ...
end
like image 108
Dogbert Avatar answered Mar 20 '23 04:03

Dogbert


There is an Elixir library which nicely wraps maps, structs, lists and tuples to provide indifferent access:

https://github.com/vic/indifferent

https://hex.pm/packages/indifferent

like image 42
Tilo Avatar answered Mar 20 '23 02:03

Tilo