Current section

Files

Jump to
tesourex lib tesourex.ex
Raw

lib/tesourex.ex

defmodule Tesourex do
def header(tesouro_csv) do
tesouro_csv |> load_file |> Enum.at(0)
end
def summary(tesouro_csv) do
[_header|rows] = tesouro_csv |> load_file
Enum.reduce(rows, %{}, &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 load_file(tesouro_csv) do
tesouro_csv
|> String.split("\n")
|> Enum.map(&(String.split(&1, ";")))
end
end