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.

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
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
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: <h1>Create Post</h1> <%= ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New

Other popular topics Top

hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
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
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New

We're in Beta

About us Mission Statement