Skip to content

Instantly share code, notes, and snippets.

@marksteve
Forked from rstacruz/_redux.ex
Last active June 4, 2016 03:38
Show Gist options
  • Select an option

  • Save marksteve/79f3cc24119187e75c5ed5c1c5a5f678 to your computer and use it in GitHub Desktop.

Select an option

Save marksteve/79f3cc24119187e75c5ed5c1c5a5f678 to your computer and use it in GitHub Desktop.
Redux.ex (elixir)
defmodule Redux do
@moduledoc """
Like redux.js, but more elixir-like
"""
defstruct reducer: nil, state: nil
@doc """
Creates a store
"""
def create_store(reducer, initial_state \\ nil) do
%Redux{reducer: reducer, state: initial_state}
|> dispatch(%{ type: "@@redux/INIT" })
end
@doc """
Returns the current state
"""
def get_state(store) do
store.state
end
@doc """
Dispatches an action
"""
def dispatch(store, action) do
Map.put(store, :state, store.reducer.(get_state(store), action))
end
end
store = Redux.create_store fn state, action ->
case action.type do
"set" ->
action.value
"add" ->
state + action.value
_ ->
state
end
end
store = store |> Redux.dispatch(%{ type: "set", value: 2 })
IO.puts(store |> Redux.get_state()) #=> 2
store = Redux.dispatch(store, %{ type: "add", value: 10 })
IO.puts(store |> Redux.get_state()) #=> 12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment