ShorterMaps 2.0 released: ES6 map shorthand for Elixir
Tired of the duplication in writing code like %{id: id, first_name: first_name, last_name: last_name}
? Dry it up with ~M{id, first_name, last_name}
.
Here are the syntactic variants the macro exposes:
-
Atom keys:
~M{a, b}
=>%{a: a, b: b}
-
String keys:
~m{a, b}
=>%{“a” => a, “b” => b}
-
Structs:
~M{%Person id, name}
=>%Person{id: id, name: name}
-
Pinned variables:
~M{^a, b}
=>%{a: ^a, b: b}
-
Ignore matching:
~M{_a, b}
=>%{a: _a, b: b}
-
Map update:
~M{old|a, b, c}
=>%{old|a: a, b: b, c: c}
-
Mixed mode:
~M{a, b: b_alt}
=>%{a: a, b: b_alt}
~M
and ~m
(atom vs. string keys) can be used to replace maps anywhere in your code: creating maps from existing variables, creating new variables while destructuring maps, pattern matching in lambdas, function heads or case statements.
See it on Github. Get it with {:shorter_maps, “~> 2.0”},
Read next Phoenix and Elm, a real use case (pt. 6)