Skip to content

Instantly share code, notes, and snippets.

@viniciusd
Created May 30, 2020 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viniciusd/a24ffa3d5644f587fedb1571e539aa79 to your computer and use it in GitHub Desktop.
Save viniciusd/a24ffa3d5644f587fedb1571e539aa79 to your computer and use it in GitHub Desktop.
-module(billing).
-export([print_bill/1]).
database() ->
[
{1111, "Hula Hoops", 21},
{1112, "Hula Hoops (Giant)", 133},
{1234, "Dry Sherry, 1lt", 540},
{4719, "Fish Fingers" , 121},
{5643, "Nappies" , 1010},
{3814, "Orange Jelly", 56}
].
database_map() ->
maps:from_list(lists:map(
fun ({Id, Name, Price}) -> {Id, {Name, Price}} end,
database()
)).
print_bill(Items) ->
print(bill(Items)).
bill(Items) ->
Database = database_map(),
Entries = lists:map(fun (Id) -> maps:get(Id, Database) end,
lists:filter(fun (Id) -> maps:is_key(Id, Database) end,
Items)),
StrEntries = lists:map(fun ({Name, Price}) -> {Name, integer_to_list(Price)} end,
Entries),
Total = {"Total", integer_to_list(lists:sum(lists:map(fun ({_Name, Price}) -> Price end, Entries)))},
LineWidth = 3 + lists:max(lists:map(fun ({Name, Price}) -> length(Name) + length(Price) end,
[Total|StrEntries])),
BillEntries = lists:map(fun ({Name, Price}) -> bill_entry(Name, Price, LineWidth) end,
StrEntries),
header(LineWidth) ++ BillEntries ++ footer(LineWidth, Total).
header(LineWidth) ->
Title = "Erlang Stores",
PaddingWidth = LineWidth-length(Title),
[
lists:duplicate(PaddingWidth div 2, " ") ++ Title ++ lists:duplicate(PaddingWidth div 2 + PaddingWidth rem 2, " "),
""
].
footer(LineWidth, {Name, Price}) ->
[
"",
bill_entry(Name,
Price,
LineWidth)
].
bill_entry(Name, Price, LineWidth) when length(Price) > 2 ->
SeparatorWidth = LineWidth - length(Name) - length(Price) - 1,
Name ++ lists:duplicate(SeparatorWidth, ".") ++ lists:sublist(Price, length(Price)-2) ++ "." ++ lists:sublist(Price, length(Price)-1, 2);
bill_entry(Name, Price, LineWidth) when length(Price) == 2 ->
SeparatorWidth = LineWidth - length(Name) - 4,
Name ++ lists:duplicate(SeparatorWidth, ".") ++ "0." ++ Price;
bill_entry(Name, Price, LineWidth) ->
SeparatorWidth = LineWidth - length(Name) - 4,
Name ++ lists:duplicate(SeparatorWidth, ".") ++ "0.0" ++ Price.
print([L|Ls]) ->
io:format("~s~n",[L]),
print(Ls);
print([]) ->
ok.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment