silviurosu

silviurosu

Convert multiple map values conditionally

I need to convert in place in a map some values only of they exist. The key can be either binary or atom.
Is there a more Elixir way to do it than my solution below?

 defp convert_time_params(params) do
    params
    |> (fn x ->
          if Map.has_key?(x, "start_time"), do: update_in(x, ["start_time"], &CalendarUtils.from_iso8601/1), else: x
        end).()
    |> (fn x ->
          if Map.has_key?(x, :start_time),
            do: update_in(x, [Access.key!(:start_time)], &CalendarUtils.from_iso8601/1),
            else: x
        end).()
    |> (fn x ->
          if Map.has_key?(x, "end_time"), do: update_in(x, ["end_time"], &CalendarUtils.from_iso8601/1), else: x
        end).()
    |> (fn x ->
          if Map.has_key?(x, :end_time),
            do: update_in(x, [Access.key!(:end_time)], &CalendarUtils.from_iso8601/1),
            else: x
        end).()
  end

The map is used in Ecto so I can not change the key type from atom to binary. I need to keep the input the same

Most Liked

hauleth

hauleth

def update_existing(map, key, fun) do
  case map do
    %{^key => old} -> %{map | key => fun.(old)}
    _ -> map
  end
end

def update_indifferent(map, key, fun) when is_atom(key) do
  map
  |> update_existing(key, fun)
  |> update_existing(Atom.to_string(key), fun)
end

And then

params
|> update_indifferent(:start_time, &CalendarUtils.from_iso8601/1)
|> update_indifferent(:end_time, &CalendarUtils.from_iso8601/1)
kip

kip

ex_cldr Core Team

I have a function called deep_map that I use in several different projects to simplify certain classes of map operations. On top of that I have other functions like atomize_keys/3 and so on. It might be useful (or it might be not :slight_smile: )

Summary

Recursively traverse a map and invoke a function
that transforms the map for each key/value pair.

Arguments

  • map is any t:map/0
  • function is a 1-arity function or function reference that
    is called for each key/value pair of the provided map. It can
    also be a 2-tuple of the form {key_function, value_function}
    • In the case where function is a single function it will be
      called with the 2-tuple argument {key, value}
    • In the case where function is of the form {key_function, value_function}
      the key_function will be called with the argument key and the value
      function will be called with the argument value
  • options is a keyword list of options. The default is []

Options

  • :level indicates the starting (and optionally ending) levels of
    the map at which the function is executed. This can
    be an integer representing one level or a range
    indicating a range of levels. The default is 1..#{@max_level}
  • :only is a term or list of terms or a check function. If it is a term
    or list of terms, the function is only called if the key of the
    map is equal to the term or in the list of terms. If :only is a
    check function then the check function is passed the {k, v} of
    the current branch in the map. It is expected to return a truthy
    value that if true signals that the argument function will be executed.
  • :except is a term or list of terms or a check function. If it is a term
    or list of terms, the function is only called if the key of the
    map is not equal to the term or not in the list of terms. If :except is a
    check function then the check function is passed the {k, v} of
    the current branch in the map. It is expected to return a truthy
    value that if true signals that the argument function will not be executed.

Notes

If both the options :only and :except are provided then the function
is called only when a term meets both criteria.

Returns

  • The map transformed by the recursive application of
    function

Examples

  iex> map = %{a: :a, b: %{c: :c}}
  iex> fun = fn
  ...>   {k, v} when is_atom(k) -> {Atom.to_string(k), v}
  ...>   other -> other
  ...> end
  iex> Cldr.Map.deep_map map, fun
  %{"a" => :a, "b" => %{"c" => :c}}
  iex> map = %{a: :a, b: %{c: :c}}
  iex> Cldr.Map.deep_map map, fun, only: :c
  %{a: :a, b: %{"c" => :c}}
  iex> Cldr.Map.deep_map map, fun, except: [:a, :b]
  %{a: :a, b: %{"c" => :c}}
  iex> Cldr.Map.deep_map map, fun, level: 2
  %{a: :a, b: %{"c" => :c}}
hauleth

hauleth

It is very important to point out that this should be used ONLY if you trust source of the binaries. If used on untrusted source then you can experience DoS when malicious party will send data with a lot different strings.

kip

kip

ex_cldr Core Team

Yes, good to point it out. The function actually has both safe and unsafe modes for exactly that reason. And all my use cases are on CLDR data (and never on user input).

Where Next?

Popular in Questions Top

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
Fl4m3Ph03n1x
Background Let’s assume I have a typical GenServer that receives messages as requests, does some operation in a DB and returns responses....
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

Other popular topics Top

peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement