Skip to content

Instantly share code, notes, and snippets.

@kipcole9
Created December 30, 2022 19:07
Show Gist options
  • Save kipcole9/4b8434c4c686f2875753919f6e28eaef to your computer and use it in GitHub Desktop.
Save kipcole9/4b8434c4c686f2875753919f6e28eaef to your computer and use it in GitHub Desktop.
Accumulate the sum of list values until a max is reached
defmodule Acc do
@moduledoc """
Recurses through a list of maps summing the amount.
If the max is exceeded it returns the list up to this point.
"""
@list [
%{amount: 23, asset: "USD"},
%{amount: 40, asset: "USD"},
%{amount: 60, asset: "USD"},
%{amount: 10, asset: "USD"},
%{amount: 100, asset: "USD"},
]
def check_amount(list \\ @list, max, sum \\ 0, acc \\ [])
# Empty list means we have summed everything so
# return the acc
def check_amount([], _max, _sum, acc) do
Enum.reverse(acc)
end
# Adding the amount would exceed max so
# return the acc
def check_amount([%{amount: amount} | _rest], max, sum, acc) when sum + amount >= max do
Enum.reverse(acc)
end
# Add the amount and continue to the rest of the list
def check_amount([%{amount: amount} = first | rest], max, sum, acc) do
check_amount(rest, max, sum + amount, [first | acc])
end
# Assert some test results
def test do
[%{amount: 23, asset: "USD"}] = Acc.check_amount(60)
[%{amount: 23, asset: "USD"}, %{amount: 40, asset: "USD"}] = Acc.check_amount(64)
[
%{amount: 23, asset: "USD"},
%{amount: 40, asset: "USD"},
%{amount: 60, asset: "USD"},
%{amount: 10, asset: "USD"},
%{amount: 100, asset: "USD"}
] = Acc.check_amount(1000)
:ok
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment