Skip to content

Instantly share code, notes, and snippets.

@jdjkelly
Last active May 6, 2017 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdjkelly/002186afcd7aa35f53ea4ab2160f76a5 to your computer and use it in GitHub Desktop.
Save jdjkelly/002186afcd7aa35f53ea4ab2160f76a5 to your computer and use it in GitHub Desktop.
reduxir

Elixir-flavored Redux:

defmodule Store do
 def start_link(reducer, preloadedState) do
   Agent.start_link(fn -> { reducer, preloadedState } end)
 end

 def start_link(reducer) do
   Agent.start_link(fn -> { reducer, nil } end)
 end

 def dispatch(store, action) do
   { reducer, state } = Agent.get(store, fn(store) -> store end)
   Agent.cast(store, fn(_) -> { reducer, reducer.(state, action) } end)
 end

 def get_state(store) do
   Agent.get(store, fn({ reducer, state }) -> state end)
 end
end

example:

iex(41)> counter = fn
...(41)>   (state, { 'INCREMENT', _ }) -> state + 1
...(41)>   (state, { 'DECREMENT', _ }) -> state - 1
...(41)>   (state, _) -> state
...(41)> end
#Function<12.118419387/2 in :erl_eval.expr/5>
iex(42)>
nil
iex(43)> {:ok, store} = Store.start_link(counter, 0)
{:ok, #PID<0.257.0>}
iex(44)>
nil
iex(45)> Store.dispatch(store, { 'INCREMENT', nil })
:ok
iex(46)>
nil
iex(47)> Store.get_state(store)
1

pattern-matching functions 👍

counter = fn
 (state, { 'INCREMENT', _ }) -> state ++
 (state, { 'DECREMENT', _ }) -> state --
 (state, _) -> state
end```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment