-
-
Save vKxni/197bd85507243b272845677e93f4cd64 to your computer and use it in GitHub Desktop.
TodoList in Elixir using GenServer.
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 TodoList do | |
use GenServer | |
@moduledoc """ | |
A TodoList add, list, find, update & remove. | |
""" | |
def start do | |
{:ok, state} = GenServer.start_link(__MODULE__, []) | |
state | |
end | |
def add(pid, value) do | |
GenServer.cast(pid, {:add, value}) | |
end | |
def list(pid) do | |
GenServer.call(pid, :list) | |
end | |
def find(pid, value) do | |
GenServer.call(pid, {:find, value}) | |
end | |
def remove(pid, index) do | |
GenServer.call(pid, {:remove, index}) | |
end | |
def complete(pid, value) do | |
GenServer.call(pid, {:complete, value}) | |
end | |
# GenServer functions. | |
def init(state) do | |
{:ok, state} | |
end | |
def handle_cast({:add, value}, state) do | |
obj = %{task: value, status: 0} | |
{:noreply, [obj | state]} | |
end | |
def handle_call(:list, _from, state) do | |
{:reply, state, state} | |
end | |
@doc """ | |
Find task details by name | |
""" | |
def handle_call({:find, value}, _from, state) do | |
val = Enum.find(state, fn x -> x.task == value end) | |
{:reply, val, state} | |
end | |
@doc """ | |
Remove and return the requested task. | |
""" | |
def handle_call({:remove, index}, _from, state) do | |
{first, rest} = List.pop_at(state, index) | |
{:reply, first, rest} | |
end | |
@doc """ | |
Update the specfic task by name to update. | |
""" | |
def handle_call({:complete, value}, _from, state) do | |
update = Enum.map(state, &update(&1, value)) | |
{:reply, update, update} | |
end | |
defp update(map, val) do | |
if(map.task == val) do | |
%{map | status: 1} | |
else | |
map | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment