I’d appreciate any advice on the code below. I’m calculating subtotals by groups of products. The products are in an unsorted list of maps. I’m calling my own subtotal function in Enum.map because some of the groups require special treatment. I’ve included one example of such a treatment.
This works, but before writing another 10 of these “treatments” I want to make sure I have the basic structure right. Also, the idea is to return the results in JSON specifying the groups, subtotals, and total. Anything I should do or not do to facilitate that?
def subtotals_by_group(list_of_products) do
list_of_products
|> Enum.group_by(fn %{group_number: g} -> g end, fn %{price: p} -> p end)
|> Enum.map(fn {group, prices} -> subtotal(group, prices) end)
end
def subtotal("PROMO1", prices) do
count = Enum.count(prices)
cond do
count < 5 ->
Enum.sum(prices)
count >= 10 ->
additional = count - 10
{:ok, ["PROMO1", (20 + additional * 4) / 1]}
true ->
{:error, "Invalid choice"}
end
end
def subtotal(group, prices) do
{:ok, [group, Enum.sum(prices)]}
end
Thank you. This is exactly what I was looking for. I have read a lot, but now I need practice to put it all together. I’m sure I read somewhere that tuples is the preferred internal representation but I guess I forgot about it.
Actually, thanks to you I found a minor bug in my code. Before, when passing less than 5 products to the special treatment function I was just returning the price without the group. Now, I fixed it like this:
def subtotal(“PROMO1”, prices) do
count = Enum.count(prices)
You’re right. It won’t make much of a difference, but you have showed me another (more elegant) way to accomplish the same thing. I love it. Big thanks!
And I think I’ll switch gears a bit on my approach; instead of working through your code I’ll start with the input/output, see if I can come up with a solution (no peeking, I promise ), and then compare.
Thank you for pointing that out. I’ll switch to the Elixir money library if this PoC goes somewhere.
@ All
Just out of curiosity, I guess Elixir follows Erlang on not allowing a binary to float conversion if the input binary is written as an integer. Any idea why the Erlang team made that decision in the first place?