-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathagent.ex
More file actions
49 lines (40 loc) · 1.04 KB
/
agent.ex
File metadata and controls
49 lines (40 loc) · 1.04 KB
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
41
42
43
44
45
46
47
48
49
defmodule ElixirScript.Agent do
@moduledoc false
def start(fun, options \\ []) do
name = if Keyword.has_key?(options, :name) do
Keyword.get(options, :name)
else
nil
end
pid = ElixirScript.Core.Store.create(fun.(), name)
{ :ok, pid }
end
def start_link(fun, options \\ []) do
name = if Keyword.has_key?(options, :name) do
Keyword.get(options, :name)
else
nil
end
pid = ElixirScript.Core.Store.create(fun.(), name)
{ :ok, pid }
end
def stop(agent) do
ElixirScript.Core.Store.remove(agent)
:ok
end
def update(agent, fun) do
current_state = ElixirScript.Core.Store.read(agent)
ElixirScript.Core.Store.update(agent, fun.(current_state))
:ok
end
def get(agent, fun) do
current_state = ElixirScript.Core.Store.read(agent)
fun.(current_state)
end
def get_and_update(agent, fun) do
current_state = ElixirScript.Core.Store.read(agent)
{val, new_state} = fun.(current_state)
ElixirScript.Core.Store.update(agent, new_state)
val
end
end