🗓️Day 14

Sunday, 21 August 2022 - Day 14 of Exhort August 2022 - Exercism (My Elixir Journey)

Exercises

Boutique Inventory

Boutique Inventory in Elixir on Exercism | View my solution

Solution

Expand to see code (spoiler alert)
defmodule BoutiqueInventory do
  def sort_by_price(inventory) do
    inventory
    |> Enum.sort_by(&(&1.price))
  end

  def with_missing_price(inventory) do
    inventory
    |> Enum.filter(&is_nil(&1.price))
  end

  def update_names(inventory, old_word, new_word) do
    inventory
    |> Enum.map(&replace_word(&1, old_word, new_word))
  end

  defp replace_word(map, old_word, new_word) do
    name = String.replace(map.name, old_word, new_word)
    Map.put(map, :name, name)
  end

  def increase_quantity(item, count) do
    qbs = Map.new(item.quantity_by_size, fn {k, v} -> {k, v + count} end)
    %{item | quantity_by_size: qbs }
  end

  def total_quantity(item) do
    item.quantity_by_size
    |> Enum.reduce(0, fn {_, v}, sum -> sum + v end)
  end
end

View gist on GitHub

Notes

Oh Zeus. I really struggled with this one. And it was so simple. I don't know why. Here's my accepted solution:

def increase_quantity(item, count) do
  qbs = Map.new(item.quantity_by_size, fn {k, v} -> {k, v + count} end)
  %{item | quantity_by_size: qbs }
end

I was trying all sorts of irrelevant things 😬. I was also thrown off by the mention of Enum.into in README.md. I guess it was an alternative to Map.new? For total_quantity/1, I used a different approach, while the exercise recommended Enum.reduce. It was the purpose of the exercise to teach you that. My initial implementation was:

item.quantity_by_size
|> Map.values
|> Enum.sum

I think it's a little easier in the eyes, but I have no idea if it's slower as I am calling a Map function and then an Enum function. Whereas reduce/3 is one function.

Overall progress

Last updated