Elixir
  • My Elixir journey
  • Why functional programming?
  • Exhort
    • 🗓️Day 22
    • 🗓️Day 21
    • 🗓️Day 20
    • 🗓️Day 19
    • 🗓️Day 18
    • 🗓️Day 17
    • 🗓️Day 16
    • 🗓️Day 15
    • 🗓️Day 14
  • Bits and pieces
    • Clean mix dependencies
    • Run tests automatically on save
    • Run tests and stop on first failure
    • How to remove Tailwind from a Phoenix project
Powered by GitBook
On this page
  • Exercises
  • Boutique Inventory
  • Overall progress
  1. Exhort

Day 14

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

PreviousDay 15NextBits and pieces

Last updated 2 years ago

Exercises

Boutique Inventory

|

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

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

🗓️
😬
Boutique Inventory in Elixir on Exercism
View my solution
View gist on GitHub
Boutique Inventory
Progress
An image showing my progress on Exercism. It's 15.4% as of Sunday, 21 August 2022.