Skip to content

Commit

Permalink
Simplify Counter
Browse files Browse the repository at this point in the history
  • Loading branch information
fredwu committed Sep 29, 2023
1 parent 0dba468 commit ce994cb
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 42 deletions.
20 changes: 4 additions & 16 deletions lib/crawler/store.ex
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ defmodule Crawler.Store do
def start_link(opts) do
children = [
{Registry, keys: :unique, name: DB},
{Counter, name: Counter}
Counter
]

Supervisor.start_link(
Expand Down Expand Up @@ -74,26 +74,14 @@ defmodule Crawler.Store do
end

def ops_inc do
__MODULE__
|> Supervisor.which_children()
|> Enum.find(&Kernel.match?({Counter, _pid, _type, [Counter]}, &1))
|> elem(1)
|> Counter.inc()
Counter.inc()
end

def ops_count do
__MODULE__
|> Supervisor.which_children()
|> Enum.find(&Kernel.match?({Counter, _pid, _type, [Counter]}, &1))
|> elem(1)
|> Counter.count()
Counter.value()
end

def ops_reset do
__MODULE__
|> Supervisor.which_children()
|> Enum.find(&Kernel.match?({Counter, _pid, _type, [Counter]}, &1))
|> elem(1)
|> Counter.reset()
Counter.reset()
end
end
35 changes: 9 additions & 26 deletions lib/crawler/store/counter.ex
Original file line number Diff line number Diff line change
@@ -1,36 +1,19 @@
defmodule Crawler.Store.Counter do
use GenServer
use Agent

def inc(pid) when is_pid(pid) do
GenServer.call(pid, :inc)
def start_link(_args) do
Agent.start_link(fn -> 0 end, name: __MODULE__)
end

def count(pid) when is_pid(pid) do
GenServer.call(pid, :count)
def value do
Agent.get(__MODULE__, & &1)
end

def reset(pid) when is_pid(pid) do
GenServer.call(pid, :reset)
def inc do
Agent.update(__MODULE__, &(&1 + 1))
end

def start_link(opts \\ []) do
GenServer.start_link(__MODULE__, 0, opts)
end

def init(args) do
{:ok, args}
end

def handle_call(:inc, _from, state) do
count = state + 1
{:reply, count, count}
end

def handle_call(:count, _from, state) do
{:reply, state, state}
end

def handle_call(:reset, _from, _state) do
{:reply, 0, 0}
def reset do
Agent.update(__MODULE__, fn _ -> 0 end)
end
end

0 comments on commit ce994cb

Please sign in to comment.