Wednesday, December 22, 2021

Elixir: clean deps

Source: How to remove unused deps from mix.lock
This removes the unused files, as well as cleans mix.lock.
> mix deps.clean --unused --unlock

Tuesday, December 21, 2021

Elixir: rename_keys

Elixir equivalent of Clojure rename_keys()
  @doc """
  Returns the map with the keys in kmap renamed to the values in kmap.
  """
  def rename_keys(map, kmap) when is_map(map) and is_map(kmap) do
    for {key, value} <- map,
        into: %{},
        do: if(new_key = Map.get(kmap, key), do: {new_key, value}, else: {key, value})
  end

Elixir: if key exists: update, otherwise: assoc

Remember Clojure: if key exists: update, otherwise: assoc? Let's do that with Elixir.
  @doc """
  If `key` exists in `map`, updates its value (assumed to be a list) by concatenating `value`.
  If `key` does not exist in `map`, creates `{key => [value]}` in `map`.
  ## Examples

    iex(35)> Tap.Worker.update_conj!(%{a: [1]}, :a, 2)
    %{a: [1, 2]}

    iex(36)> Tap.Worker.update_conj!(%{a: [1]}, :b, 2)
    %{a: [1], b: [2]}

  """
  @spec update_conj!(map, any, any) :: map
  def update_conj!(map, key, value) when is_map(map) do
    Map.update(map, key, [value], fn
      existing_values when is_list(existing_values) ->
        existing_values ++ [value]

      existing_value ->
        raise(ArgumentError, "Value is not a list: #{inspect(existing_value)}")
    end)
  end

Elixir: map to struct

Courtesy of Jose Valim: (https://groups.google.com/forum/#!msg/elixir-lang-talk/6geXOLUeIpI/L9einu4EEAAJ).
  def to_struct(kind, attrs) do
    struct = struct(kind)

    Logger.debug("attrs = #{inspect(attrs)}")

    Enum.reduce(Map.to_list(struct), struct, fn {k, _}, acc ->
      case Map.fetch(attrs, k) do
        {:ok, v} -> %{acc | k => v}
        :error -> acc
      end
    end)
  end