Created
October 11, 2015 20:55
-
-
Save vothane/e88017c239b76eda8bcf to your computer and use it in GitHub Desktop.
replacing command pattern with functions in Elixir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule CashRegister do | |
def new do | |
Agent.start_link(fn -> 0 end) | |
end | |
def add(pid, amount) do | |
Agent.update(pid, fn(register) -> register + amount end) | |
end | |
def reset(pid) do | |
Agent.update(pid, fn(register) -> 0 end) | |
end | |
def get(pid) do | |
Agent.get(pid, fn(register) -> register end) | |
end | |
end | |
ExUnit.start | |
defmodule CashRegisterTest do | |
use ExUnit.Case | |
test "cashier" do | |
{:ok, pid} = CashRegister.new | |
assert CashRegister.get(pid) == 0 | |
CashRegister.add(pid, 100) | |
assert CashRegister.get(pid)== 100 | |
CashRegister.add(pid, 20) | |
assert CashRegister.get(pid)== 120 | |
CashRegister.reset(pid) | |
assert CashRegister.get(pid)== 0 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment