Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add practice exercise ledger #1367

Merged
merged 4 commits into from
Sep 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -2298,6 +2298,25 @@
"practices": [],
"difficulty": 6
},
{
"slug": "ledger",
"name": "Ledger",
"uuid": "a3134be3-ac2f-4612-9cd2-4f2a6a4de48f",
"prerequisites": [
"if",
"lists",
"atoms",
"strings",
"maps",
"dates-and-time",
"multiple-clause-functions",
"pattern-matching"
],
"practices": [
"multiple-clause-functions"
],
"difficulty": 6
},
{
"slug": "list-ops",
"name": "List Ops",
Expand Down
14 changes: 14 additions & 0 deletions exercises/practice/ledger/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Instructions

Refactor a ledger printer.

The ledger exercise is a refactoring exercise.
There is code that prints a nicely formatted ledger, given a locale (American or Dutch) and a currency (US dollar or euro).
The code however is rather badly written, though (somewhat surprisingly) it consistently passes the test suite.

Rewrite this code.
Remember that in refactoring the trick is to make small steps that keep the tests passing.
That way you can always quickly go back to a working version.
Version control tools like git can help here as well.

Please keep a log of what changes you've made and make a comment on the exercise containing that log, this will help reviewers.
4 changes: 4 additions & 0 deletions exercises/practice/ledger/.formatter.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]
26 changes: 26 additions & 0 deletions exercises/practice/ledger/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# The directory Mix will write compiled artifacts to.
/_build/

# If you run "mix test --cover", coverage assets end up here.
/cover/

# The directory Mix downloads your dependencies sources to.
/deps/

# Where third-party dependencies like ExDoc output generated docs.
/doc/

# Ignore .fetch files in case you like to edit your project deps locally.
/.fetch

# If the VM crashes, it generates a dump, let's ignore it too.
erl_crash.dump

# Also ignore archive artifacts (built via "mix archive.build").
*.ez

# Ignore package tarball (built via "mix hex.build").
ledger-*.tar

# Temporary files, for example, from tests.
/tmp/
17 changes: 17 additions & 0 deletions exercises/practice/ledger/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"authors": [
"jiegillet"
],
"files": {
"solution": [
"lib/ledger.ex"
],
"test": [
"test/ledger_test.exs"
],
"example": [
".meta/example.ex"
]
},
"blurb": "Refactor a ledger printer."
}
127 changes: 127 additions & 0 deletions exercises/practice/ledger/.meta/example.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
defmodule Ledger do
@doc """
Format the given entries given a currency and locale
"""
@type currency :: :usd | :eur
@type locale :: :en_US | :nl_NL
@type entry :: %{amount_in_cents: integer(), date: Date.t(), description: String.t()}

@spec format_entries(currency(), locale(), list(entry())) :: String.t()
def format_entries(currency, locale, entries) do
header = header(locale)

entries =
entries
|> Enum.sort(&compare_entries/2)
|> Enum.map(fn entry -> format_entry(currency, locale, entry) end)

Enum.join([header | entries], "\n") <> "\n"
end

defp header(:en_US), do: "Date | Description | Change "
defp header(:nl_NL), do: "Datum | Omschrijving | Verandering "

defp compare_entries(a, b) do
case Date.compare(a.date, b.date) do
:lt ->
true

:gt ->
false

:eq ->
cond do
a.description < b.description -> true
a.description > b.description -> false
true -> a.amount_in_cents <= b.amount_in_cents
end
end
end

@description_width 25
@amount_width 13
defp format_entry(currency, locale, %{
amount_in_cents: amount,
date: date,
description: description
}) do
date = format_date(date, locale)

amount =
amount
|> format_amount(currency, locale)
|> String.pad_leading(@amount_width, " ")

description =
if String.length(description) > @description_width do
String.slice(description, 0, @description_width - 3) <> "..."
else
String.pad_trailing(description, @description_width, " ")
end

Enum.join([date, description, amount], " | ")
end

defp format_date(date, :en_US) do
year = date.year
month = date.month |> to_string() |> String.pad_leading(2, "0")
day = date.day |> to_string() |> String.pad_leading(2, "0")
Enum.join([month, day, year], "/")
end

defp format_date(date, :nl_NL) do
year = date.year
month = date.month |> to_string() |> String.pad_leading(2, "0")
day = date.day |> to_string() |> String.pad_leading(2, "0")
Enum.join([day, month, year], "-")
end

defp format_amount(amount, currency, :en_US) do
currency = format_currency(currency)
number = format_number(abs(amount), ".", ",")

if amount >= 0 do
" #{currency}#{number} "
else
"(#{currency}#{number})"
end
end

defp format_amount(amount, currency, :nl_NL) do
currency = format_currency(currency)
number = format_number(abs(amount), ",", ".")

if amount >= 0 do
"#{currency} #{number} "
else
"#{currency} -#{number} "
end
end

defp format_currency(:usd), do: "$"
defp format_currency(:eur), do: "€"

defp format_number(number, decimal_separator, thousand_separator) do
decimal = number |> rem(100) |> to_string() |> String.pad_leading(2, "0")
whole = number |> div(100) |> to_string() |> chunk() |> Enum.join(thousand_separator)
whole <> decimal_separator <> decimal
end

defp chunk(number) do
case String.length(number) do
0 ->
[]

n when n < 3 ->
[number]

n when rem(n, 3) == 0 ->
{chunk, rest} = String.split_at(number, 3)
[chunk | chunk(rest)]

n ->
{chunk, rest} = String.split_at(number, rem(n, 3))
[chunk | chunk(rest)]
end
end
end
43 changes: 43 additions & 0 deletions exercises/practice/ledger/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[d131ecae-a30e-436c-b8f3-858039a27234]
description = "empty ledger"

[ce4618d2-9379-4eca-b207-9df1c4ec8aaa]
description = "one entry"

[8d02e9cb-e6ee-4b77-9ce4-e5aec8eb5ccb]
description = "credit and debit"

[502c4106-0371-4e7c-a7d8-9ce33f16ccb1]
description = "multiple entries on same date ordered by description"

[29dd3659-6c2d-4380-94a8-6d96086e28e1]
description = "final order tie breaker is change"

[9b9712a6-f779-4f5c-a759-af65615fcbb9]
description = "overlong description is truncated"

[67318aad-af53-4f3d-aa19-1293b4d4c924]
description = "euros"

[bdc499b6-51f5-4117-95f2-43cb6737208e]
description = "Dutch locale"

[86591cd4-1379-4208-ae54-0ee2652b4670]
description = "Dutch locale and euros"

[876bcec8-d7d7-4ba4-82bd-b836ac87c5d2]
description = "Dutch negative number with 3 digits before decimal point"

[29670d1c-56be-492a-9c5e-427e4b766309]
description = "American negative number with 3 digits before decimal point"
104 changes: 104 additions & 0 deletions exercises/practice/ledger/lib/ledger.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
defmodule Ledger do
@doc """
Format the given entries given a currency and locale
"""
@type currency :: :usd | :eur
@type locale :: :en_US | :nl_NL
@type entry :: %{amount_in_cents: integer(), date: Date.t(), description: String.t()}

@spec format_entries(currency(), locale(), list(entry())) :: String.t()
def format_entries(currency, locale, entries) do
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe the locale could also get its own custom type?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought about it, I think I decided not to because somehow I thought capital letter were not allowed in atoms... But that's silly, so I made it a type after all :)

header =
if locale == :en_US do
"Date | Description | Change \n"
else
"Datum | Omschrijving | Verandering \n"
end

if entries == [] do
header
else
entries =
Enum.sort(entries, fn a, b ->
cond do
a.date.day < b.date.day -> true
a.date.day > b.date.day -> false
a.description < b.description -> true
a.description > b.description -> false
true -> a.amount_in_cents <= b.amount_in_cents
end
end)
|> Enum.map(fn entry -> format_entry(currency, locale, entry) end)
|> Enum.join("\n")

header <> entries <> "\n"
end
end

defp format_entry(currency, locale, entry) do
year = entry.date.year |> to_string()
month = entry.date.month |> to_string() |> String.pad_leading(2, "0")
day = entry.date.day |> to_string() |> String.pad_leading(2, "0")

date =
if locale == :en_US do
month <> "/" <> day <> "/" <> year <> " "
else
day <> "-" <> month <> "-" <> year <> " "
end

number =
if locale == :en_US do
decimal =
entry.amount_in_cents |> abs |> rem(100) |> to_string() |> String.pad_leading(2, "0")

whole =
if abs(div(entry.amount_in_cents, 100)) < 1000 do
abs(div(entry.amount_in_cents, 100)) |> to_string()
else
to_string(div(abs(div(entry.amount_in_cents, 100)), 1000)) <>
"," <> to_string(rem(abs(div(entry.amount_in_cents, 100)), 1000))
end

whole <> "." <> decimal
else
decimal =
entry.amount_in_cents |> abs |> rem(100) |> to_string() |> String.pad_leading(2, "0")

whole =
if abs(div(entry.amount_in_cents, 100)) < 1000 do
abs(div(entry.amount_in_cents, 100)) |> to_string()
else
to_string(div(abs(div(entry.amount_in_cents, 100)), 1000)) <>
"." <> to_string(rem(abs(div(entry.amount_in_cents, 100)), 1000))
end

whole <> "," <> decimal
end

amount =
if entry.amount_in_cents >= 0 do
if locale == :en_US do
" #{if(currency == :eur, do: "€", else: "$")}#{number} "
else
" #{if(currency == :eur, do: "€", else: "$")} #{number} "
end
else
if locale == :en_US do
" (#{if(currency == :eur, do: "€", else: "$")}#{number})"
else
" #{if(currency == :eur, do: "€", else: "$")} -#{number} "
end
end
|> String.pad_leading(14, " ")

description =
if entry.description |> String.length() > 26 do
" " <> String.slice(entry.description, 0, 22) <> "..."
else
" " <> String.pad_trailing(entry.description, 25, " ")
end

date <> "|" <> description <> " |" <> amount
end
end
28 changes: 28 additions & 0 deletions exercises/practice/ledger/mix.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
defmodule Ledger.MixProject do
use Mix.Project

def project do
[
app: :ledger,
version: "0.1.0",
# elixir: "~> 1.10",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end

# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end

# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end
Loading