new to Elixir and functional programming in general. I am looking to merge a new item into a list of existing items. When the "key" of the new item is already present in the list, I need to update the corresponding item in the list, otherwise I add the new item to the list.
I've come up with the below, but it seems a little clunky, is there a better way to be doing this?
Much thanks!
defmodule Test.LineItem do
defstruct product_id: nil, quantity: nil
end
defmodule Test do
alias Test.LineItem
def main do
existing_items = [
%LineItem{product_id: 1, quantity: 123},
%LineItem{product_id: 2, quantity: 234},
%LineItem{product_id: 3, quantity: 345}
]
IO.puts "*** SHOULD BE 3 ITEMS, QUANTITY OF 123, 244, 345 ***"
new_item = %{product_id: 2, quantity: 10}
Enum.each merge(existing_items, new_item), &IO.inspect(&1)
IO.puts "*** SHOULD BE 4 ITEMS, QUANTITY OF 10, 123, 234, 345 ***"
new_item = %{product_id: 4, quantity: 10}
Enum.each merge(existing_items, new_item), &IO.inspect(&1)
:ok
end
def merge(existing_items, new_item) do
existing_items = existing_items |> Enum.map(&Map.from_struct/1)
lines = Enum.map(existing_items, fn(x) ->
if x.product_id == new_item.product_id do
%{product_id: x.product_id, quantity: x.quantity + new_item.quantity}
else
x
end
end)
unless Enum.find(lines, &(Map.get(&1, :product_id)==new_item.product_id)) do
[new_item | lines]
else
lines
end
end
end