Skip to content

Commit a1aa512

Browse files
bank solution
1 parent 59dd708 commit a1aa512

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

lessons/otp-concurrency/simple_bank/lib/simple_bank.ex

+25-1
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,21 @@ defmodule SimpleBank do
5959
end
6060

6161
@spec withdrawl(pid(), String.t(), pos_integer()) :: {:ok, {pos_integer(), pos_integer()}} | {:error, reason}
62-
def withdrawl(bank_pid, account_id, amount) do
62+
def withdrawl(bank_pid, account_id, amount) when is_integer(amount) and amount > 0 do
63+
case get_account_by_id(bank_pid, account_id) do
64+
nil -> {:error, :missing_account}
65+
account ->
66+
if account.balance < amount do
67+
{:error, :insufficient_funds}
68+
else
69+
account = GenServer.call(bank_pid, {:withdrawal, account, amount})
70+
{:ok, account.balance}
71+
end
72+
end
73+
end
74+
75+
def withdrawl(_bank_pid, _account_id, amount) when is_integer(amount) and amount <= 0 do
76+
{:error, :pos_integer_only}
6377
end
6478

6579
def init(initial_state) do
@@ -90,10 +104,20 @@ defmodule SimpleBank do
90104
{:reply, account, new_state}
91105
end
92106

107+
def handle_call({:withdrawal, account, amount}, _from, state) do
108+
account = do_withdrawal(account, amount)
109+
new_state = update_account_in_state(account, state)
110+
{:reply, account, new_state}
111+
end
112+
93113
def do_deposit(account, amount) do
94114
Map.put(account, :balance, account.balance + amount)
95115
end
96116

117+
def do_withdrawal(account, amount) do
118+
Map.put(account, :balance, account.balance - amount)
119+
end
120+
97121
def update_account_in_state(account, state) do
98122
accounts = Enum.reject(state, fn a -> a.id == account.id end)
99123
[accounts | account]

lessons/otp-concurrency/simple_bank/test/simple_bank_test.exs

+3-3
Original file line numberDiff line numberDiff line change
@@ -45,15 +45,15 @@ defmodule SimpleBankTest do
4545

4646
describe "withdrawl/3" do
4747
test "decreases the account balance by the withdrawn amount", %{bank: bank_pid} do
48-
assert {:ok, 100} == SimpleBank.withdrawl(bank_pid, "test_id", 10)
48+
assert {:ok, 90} == SimpleBank.withdrawl(bank_pid, "test_id", 10)
4949
end
5050

5151
test "does not negative ammount balances", %{bank: bank_pid} do
52-
assert {:error, :insufficient_funds} == SimpleBank.withdrawl(bank_pid, "test_id", -1)
52+
assert {:error, :insufficient_funds} == SimpleBank.withdrawl(bank_pid, "test_id", 1000)
5353
end
5454

5555
test "does not allow withdrawls of negative amounts", %{bank: bank_pid} do
56-
assert {:error, :pos_integer_only} == SimpleBank.withdrawl(bank_pid, "test_id", 1000)
56+
assert {:error, :pos_integer_only} == SimpleBank.withdrawl(bank_pid, "test_id", -1)
5757
end
5858

5959
test "raises an error if the account does not exist", %{bank: bank_pid} do

0 commit comments

Comments
 (0)