|
1 | 1 | defmodule ElixirScript.Agent do |
2 | | - @moduledoc false |
| 2 | + @moduledoc false |
| 3 | + require JS |
3 | 4 |
|
4 | 5 | def start(fun, options \\ []) do |
5 | | - pid = spawn(fn() -> Process.sleep(:infinity) end) |
| 6 | + pid = JS.new Elixir.Core.PID, [] |
6 | 7 |
|
7 | | - if Elixir.Keyword.has_key?(options, :name) do |
8 | | - Process.register(pid, Elixir.Keyword.get(options, :name)) |
| 8 | + name = if Elixir.Keyword.has_key?(options, :name) do |
| 9 | + Elixir.Keyword.get(options, :name) |
| 10 | + else |
| 11 | + nil |
9 | 12 | end |
10 | 13 |
|
11 | | - Elixir.Core.Store.create(pid, fun.()) |
| 14 | + Elixir.Core.Store.create(pid, fun.(), name) |
12 | 15 | { :ok, pid } |
13 | 16 | end |
14 | 17 |
|
15 | 18 | def start_link(fun, options \\ []) do |
16 | | - pid = spawn_link(fn() -> Process.sleep(:infinity) end) |
| 19 | + pid = JS.new Elixir.Core.PID, [] |
17 | 20 |
|
18 | | - if Elixir.Keyword.has_key?(options, :name) do |
19 | | - Process.register(pid, Elixir.Keyword.get(options, :name)) |
| 21 | + name = if Elixir.Keyword.has_key?(options, :name) do |
| 22 | + Elixir.Keyword.get(options, :name) |
| 23 | + else |
| 24 | + nil |
20 | 25 | end |
21 | 26 |
|
22 | | - Elixir.Core.Store.create(pid, fun.()) |
| 27 | + Elixir.Core.Store.create(pid, fun.(), name) |
23 | 28 | { :ok, pid } |
24 | 29 | end |
25 | 30 |
|
26 | 31 | def stop(agent) do |
27 | | - Process.exit(agent) |
| 32 | + Elixir.Core.Store.remove(agent) |
28 | 33 | :ok |
29 | 34 | end |
30 | 35 |
|
31 | 36 | def update(agent, fun) do |
32 | | - pid = Elixir.Core.processes.pidof(agent) |
33 | | - current_state = Elixir.Core.Store.read(pid) |
34 | | - Elixir.Core.Store.update(pid, fun.(current_state)) |
| 37 | + current_state = Elixir.Core.Store.read(agent) |
| 38 | + Elixir.Core.Store.update(agent, fun.(current_state)) |
35 | 39 | :ok |
36 | 40 | end |
37 | 41 |
|
38 | 42 | def get(agent, fun) do |
39 | | - pid = Elixir.Core.processes.pidof(agent) |
40 | | - current_state = Elixir.Core.Store.read(pid) |
| 43 | + current_state = Elixir.Core.Store.read(agent) |
41 | 44 | fun.(current_state) |
42 | 45 | end |
43 | 46 |
|
44 | 47 | def get_and_update(agent, fun) do |
45 | | - pid = Elixir.Core.processes.pidof(agent) |
46 | | - current_state = Elixir.Core.Store.read(pid) |
| 48 | + current_state = Elixir.Core.Store.read(agent) |
47 | 49 | {val, new_state} = fun.(current_state) |
48 | | - Elixir.Core.Store.update(pid, new_state) |
| 50 | + Elixir.Core.Store.update(agent, new_state) |
49 | 51 | val |
50 | 52 | end |
51 | 53 |
|
|
0 commit comments