Current section

Files

Jump to
tesourex lib tesourex.ex
Raw

lib/tesourex.ex

defmodule Tesourex do
def header(tesouro_csv) do
tesouro_csv |> split_fields |> Enum.at(0)
end
def summary(tesouro_csv) do
tesouro_csv
|> split_fields
|> Enum.reduce(%{}, &group_by_name_and_most_recent/2)
end
defp group_by_name_and_most_recent([""], acc), do: acc
defp group_by_name_and_most_recent(row, acc) do
Map.update(acc, name_with_year(row), row, fn current ->
most_recent(current, row)
end)
end
defp most_recent(a, b) do
[_,_,date_a|_] = a
[_,_,date_b|_] = b
case Date.compare(to_date(date_a), to_date(date_b)) do
:gt -> a
_ -> b
end
end
defp to_date(tesouro_date) do
parts = tesouro_date
|> String.split("/")
|> Enum.reverse
|> Enum.map(&String.to_integer/1)
{:ok, date} = apply(&Date.new/3, parts)
date
end
defp name_with_year([name,date|_]) do
year = date
|> String.split("/")
|> Enum.at(2)
"#{name} #{year}"
end
defp split_fields(tesouro_csv) do
tesouro_csv
|> Stream.map(&(&1 |> String.trim() |> String.split(";")))
end
end