Created
December 6, 2023 12:55
-
-
Save hl/2ba6690e7c686d020b87791a4f107275 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule James do | |
@moduledoc """ | |
Agent: James Bond | |
""" | |
defmodule State do | |
@moduledoc """ | |
Data module to defined and modify state. | |
""" | |
defstruct [:id, :name] | |
@opaque t :: %__MODULE__{ | |
id: id(), | |
name: name() | nil | |
} | |
@type key :: atom() | |
@type value :: any() | |
@type id :: String.t() | |
@type name :: String.t() | |
@spec new(id()) :: t() | |
def new(id), do: struct(__MODULE__, id: id) | |
@spec get(t, key()) :: value() | |
def get(%__MODULE__{} = state, key), do: Map.get(state, key) | |
@spec put(t, atom(), value()) :: t() | |
def put(%__MODULE__{} = state, key, value), do: Map.put(state, key, value) | |
end | |
use Agent | |
@spec start_link(State.id()) :: Agent.on_start() | |
def start_link(id) do | |
Agent.start_link(State, :new, [id], name: __MODULE__) | |
end | |
@spec state() :: State.t() | |
def state do | |
Agent.get(__MODULE__, Function, :identity, []) | |
end | |
@spec get(State.key()) :: any() | |
def get(key) do | |
Agent.get(__MODULE__, State, :get, [key]) | |
end | |
@spec put(State.key(), State.value()) :: :ok | |
def put(key, value) do | |
Agent.update(__MODULE__, State, :put, [key, value]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment