exercism/elixir/boutique-inventory/lib/boutique_inventory.ex

42 lines
1023 B
Elixir
Raw Normal View History

2023-12-20 04:54:39 +00:00
defmodule BoutiqueInventory do
def sort_by_price(inventory) do
Enum.sort_by(inventory, & &1[:price])
end
def with_missing_price(inventory) do
Enum.filter(inventory, &(!&1[:price]))
end
def update_names(inventory, old_word, new_word) do
inventory
|> Enum.map(fn item ->
new_name = String.replace(item.name, old_word, new_word)
%{item | name: new_name}
end)
end
def increase_quantity(item, count) do
item
|> Map.get_and_update(:quantity_by_size, fn quantities ->
{quantities, update_quantities(quantities, count)}
end)
|> elem(1)
end
defp update_quantities(quantities, count) do
quantities
|> Map.to_list()
|> Enum.map(&increase_size_quantity(&1, count))
|> Enum.into(%{})
end
defp increase_size_quantity({key, value}, count), do: {key, value + count}
def total_quantity(item) do
item.quantity_by_size
|> Enum.reduce(0, &sum_total_quantity/2)
end
defp sum_total_quantity({_key, value}, acc), do: acc + value
end