-
Notifications
You must be signed in to change notification settings - Fork 1
/
paragraph.ex
40 lines (31 loc) · 1.03 KB
/
paragraph.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
defmodule Paragraph do
use GenServer
require Logger
alias AppAnimal.Cursor
@impl true
def init(%{text: text, cursor: cursor}) do
state = %{text: text, cursor: cursor}
"starts with #{Cursor.pretty(state)}" |> Logger.info
{:ok, state}
end
@impl true
def handle_call({:observer, observer}, _from, state) do
{:reply, :ok, Map.put(state, :observer, observer)}
end
@impl true
def handle_call({:add, grapheme}, _from, state),
do: {:reply, :ok, add(grapheme, state)}
@impl true
def handle_cast({:add, grapheme}, state),
do: {:noreply, add(grapheme, state)}
defp add(grapheme, state) do
"is adding #{inspect grapheme}" |> Logger.info
{prefix, suffix} = String.split_at(state.text, state.cursor)
next_text = prefix <> grapheme <> suffix
next_cursor = state.cursor + 1
next_state = %{state | text: next_text, cursor: next_cursor}
GenServer.cast(state.observer, {:added, grapheme})
Logger.info("has been modified into #{Cursor.pretty(next_state)}")
next_state
end
end