Skip to content

Commit b83e915

Browse files
author
Bernard Pietraga
committed
Add solution for exercise 1 from chapter 17
1 parent 7d10731 commit b83e915

File tree

3 files changed

+67
-1
lines changed

3 files changed

+67
-1
lines changed

chapter_17/sequence/lib/sequence/application.ex

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ defmodule Sequence.Application do
1111
# Define workers and child supervisors to be supervised
1212
children = [
1313
# Starts a worker by calling: Sequence.Worker.start_link(arg1, arg2, arg3)
14-
# worker(Sequence.Worker, [arg1, arg2, arg3]),
14+
worker(Sequence.Server, [123]),
1515
]
1616

1717
# See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
defmodule Sequence.Server do
2+
use GenServer
3+
4+
def start_link(stack), do:
5+
GenServer.start_link(__MODULE__, stack, name: __MODULE__)
6+
7+
def pop, do:
8+
GenServer.call(__MODULE__, :pop)
9+
10+
def push(element), do:
11+
GenServer.cast(__MODULE__, {:push, element})
12+
13+
def exit, do:
14+
GenServer.cast(__MODULE__, {:push, :exit})
15+
16+
def handle_call({:set_stack, stack}, _from, _stack), do:
17+
{:reply, stack, stack}
18+
19+
def handle_call(:pop, _from, []), do:
20+
{:reply, [], []}
21+
def handle_call(:pop, _from, [head | tail]), do:
22+
{:reply, head, tail}
23+
24+
def handle_cast({:push, :exit}, list), do:
25+
{:stop, :shutdown, list}
26+
27+
def handle_cast({:push, element}, list), do:
28+
{:noreply, [element | list]}
29+
30+
def terminate(reason, status) do
31+
IO.puts "Server shutdown, reason: #{reason}, current_status: #{status}"
32+
:ok
33+
end
34+
end
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
defmodule SequenceServerTest do
2+
use ExUnit.Case, async: true
3+
doctest Sequence
4+
5+
test "pop removes first element (not like normal pop)" do
6+
{:ok, pid} = GenServer.start_link(Sequence.Server, [5, "cat", 9])
7+
expected = GenServer.call(pid, :pop)
8+
second_expected = GenServer.call(pid, :pop)
9+
third_expected = GenServer.call(pid, :pop)
10+
fourth_expected = GenServer.call(pid, :pop)
11+
12+
assert expected == 5
13+
assert second_expected == "cat"
14+
assert third_expected == 9
15+
assert fourth_expected == []
16+
end
17+
18+
19+
test "push add element to array" do
20+
{:ok, pid} = GenServer.start_link(Sequence.Server, [1, 2, 3])
21+
GenServer.cast(pid, {:push, "mayoness"})
22+
expected = GenServer.call(pid, :pop)
23+
24+
assert expected == "mayoness"
25+
end
26+
27+
test "set_stack does its job" do
28+
{:ok, pid} = GenServer.start_link(Sequence.Server, [1, 2, 3])
29+
expected = GenServer.call(pid, {:set_stack, ["a", "b", "c"]})
30+
assert expected == ["a", "b", "c"]
31+
end
32+
end

0 commit comments

Comments
 (0)